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

时间:2017-10-22 03:03:01

标签: python python-3.x list for-loop set

nums = [13, 1, 2, 13, 2, 1, 13]
index = [1,3]

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

print(unwanted)

有没有什么方法可以在一行中间3行代码? 所以,像

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

我是python的新手,并试图学习什么,"我为我的nums ...."确实。 在典型的for循环中,我们只写

for i in item_list
    ....

我们不会添加"我" " for"。我想知道"我"正在"为#34;做

1 个答案:

答案 0 :(得分:2)

是的,你可以:

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和每个{{1}在nums中,只有当它不在i

时才会收集它