在一个lin中使用for循环生成一个新集合

2024-10-01 09:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

print(unwanted)

有什么方法可以让我在一行代码的中间3行? 所以,有点像

^{pr2}$

我是python的新手,我想了解“innums中的I for I…”是什么意思。 在典型的for循环中,我们只需编写

for i in item_list
    ....

我们不会在“for”前面加上“i”。我想知道“我”在“为了”前面做什么。在


Tags: 方法代码inaddforindexitemprint
1条回答
网友
1楼 · 发布于 2024-10-01 09:19:55

是的,您可以:

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

至于你的例子:

^{pr2}$

python的一个优点是你可以像读一本书中的一个句子一样阅读它:所以i for i in nums if i not in unwanted意味着你迭代nums,而对于nums中的每个{},只有当它不在unwanted中时,你才会收集它

相关问题 更多 >