python:从列表创建列表返回较少的项目

标签 python list for-loop double

我有一个文件列表,我用它创建:

files=[f for f in os.listdir(source) if f.endswith('.tif')]
print(len(files))
264

此列表包含 264 个文件,即

 ...,'NL-HnWFA_2244_157.tif', 'NL-HnWFA_2244_158-001.tif', 'NL-HnWFA_2244_158-002.tif', 'NL-HnWFA_2244_159.tif', ...

从这个文件列表中,我想通过执行以下操作来减去库存(“157”部分):

inventories = []
for file in files:
  inventories.append(file.split('_')[2].split('-')[0].split('.')[0])
print(len(inventories))  
264

然后我的列表中有 264 个项目
但是,如果我发出命令:

inventories = {fn.split('_')[2].split('-')[0].split('.')[0] for fn in files}
print(len(inventories))
263

double 值已被省略,只有 263 项。

为什么第二个语句中省略了 double 值?
我仍然可以(以某种方式)获得第一个语句中的 double 值吗?

最佳答案

这是因为set(正如您所做的{...}),始终使序列不重复值。

对此你无能为力。

所以你必须使用列表理解。

演示:

>>> a=[1,2,3,3]
>>> set(a)
{1, 2, 3}
>>> {i for i in a}
{1, 2, 3}
>>> {*a}
{1, 2, 3}
>>> 

就像这个 docs :

Sets are mutable unordered collections of unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference.

关于python:从列表创建列表返回较少的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517209/

相关文章:

python - 如何使以下文本出现在我的 python 程序中?

python - 根据不同的索引位置删除列表列表中的公共(public)项

java - 制作任何东西的通用参数化类型

JavaScript for 循环,关于索引

python - 如何从字典中检索多个项目对

python - 如何在使用 django.test 测试用例时从 View 获取对象

python - Django 1.11 密码重置 token 的生成发生意外变化

python - 我的时间数据 "does not match format"。如何正确格式化我的日期时间?

python - 在 Python 中,为什么我的 for 循环只在特定数字之前的数字是数组中的最后一个时才排除该数字?

c# - 增加 int 数组的更优雅的方法?