Skip to main content
 首页 » 编程设计

python之在一行中使用 for 循环制作一个新集合

2024年08月19日36zhujiabin

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 的新手,正在尝试学习“i for i in nums ....”的作用。 在典型的 for 循环中,我们只写

for i in item_list 
    .... 

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

请您参考如下方法:

是的,你可以:

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 并且对于 nums 中的每个 i 只有当它不在 unwanted

中时你才会收集它