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

Eri*_*Kim 4 python for-loop list set python-3.x

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

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

print(unwanted)
Run Code Online (Sandbox Code Playgroud)

有什么方法可以将中间 3 行代码合并为一行吗?所以,像

new = [i for i in nums if i not in unwanted]
Run Code Online (Sandbox Code Playgroud)

我是 python 新手,试图了解“i for i in nums ....”的作用。在典型的 for 循环中,我们只需编写

for i in item_list
    ....
Run Code Online (Sandbox Code Playgroud)

并且我们不在“for”前面添加“i”。我想知道“for”前面的“i”在做什么。

alf*_*sin 8

是的你可以:

unwanted = set(nums[i] for i in index)
Run Code Online (Sandbox Code Playgroud)

至于你的例子:

new = [i for i in nums if i not in unwanted]
Run Code Online (Sandbox Code Playgroud)

python 的好处之一是,你可以像阅读书中的句子一样阅读它:soi for i in nums if i not in unwanted意味着你会迭代nums,并且对于每个iin nums,只有当它不在 nums 中时,你才会收集它unwanted