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

标签 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 的新手,正在尝试学习“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

中时你才会收集它

关于python - 在一行中使用 for 循环制作一个新集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46870084/

相关文章:

python - 在 djangoviews.py 代码中使用数组 - 这是一个好习惯吗?

python - DateField 'str' 对象没有属性 'year'

python - 从字符串中解析格式奇怪的时间表达式

python - 如何在Python中用ASCII字符(\u9078)分割行

python - 使用 np.where 和 list 来生成一系列而不是 ndarray 的替代方案更适合转换为数据帧?

python - pylab导入错误: No module named _thread

Python正则表达式与字符串匹配的问题

python - 基于关闭年份条件 Python 添加和减去值

python - 迭代元组,获取下一项

python - 如果 pandas series 的值是一个列表,如何获取每个元素的子列表?