【问题标题】:making a new set using for loop, in one line在一行中使用 for 循环创建一个新集合
【发布时间】:2018-04-02 20:43:56
【问题描述】:
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”。我想知道“i”在“for”前面做什么。

【问题讨论】:

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


    【解决方案1】:

    是的,你可以:

    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 在 nums 中你会仅当它不在 unwanted 中时才收集它

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 2020-02-23
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多