2017-10-22 130 views
1
nums = [13, 1, 2, 13, 2, 1, 13] 
index = [1,3] 

unwanted = set() 
for i in index: 
    unwanted.add(nums[i]) 

print(unwanted) 

有沒有什麼辦法可以讓我在中間的3行代碼在一行中? 所以,像使用for循環創建一個新的集合,在一行中

new = [i for i in nums if i not in unwanted] 

我是新來的Python和努力學習的東西,「我爲我在NUMS ......」的確。 在一個典型的循環中,我們只寫

for i in item_list 
    .... 

,我們不加入「爲」前「我」。我想知道「我」在「for」前面做了什麼。

回答

1

是,您可以:

unwanted = set(nums[i] for i in index) 

至於你的例子:

new = [i for i in nums if i not in unwanted] 

關於Python的好東西之一是,你可以,如果你是從一個讀句子閱讀書:所以i for i in nums if i not in unwanted意味着你迭代nums和每個i的數量,你會收集它只有當它不在unwanted