我有一个文件列表,我用它创建:
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/