使用for循环创建一个新的集合,在一行中

使用for循环创建一个新的集合,在一行中

问题描述:

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”前面做了什么。

是,您可以:

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