本文介绍了如何在python中构造一组列表项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在python中有一个文件名list
,我想从所有文件名中构造一个set
.
I have a list
of filenames in python and I would want to construct a set
out of all the filenames.
filelist=[]
for filename in filelist:
set(filename)
这似乎不起作用.该怎么办?
This does not seem to work. How can do this?
推荐答案
如果您具有可哈希对象的列表(文件名可能是字符串,因此应该算在内):
If you have a list of hashable objects (filenames would probably be strings, so they should count):
lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis]
您可以直接构造集合:
s = set(lst)
实际上,set
可以与任何可迭代对象一起使用!(鸭子输入不是很好吗?)
In fact, set
will work this way with any iterable object! (Isn't duck typing great?)
如果要反复进行:
s = set()
for item in iterable:
s.add(item)
但是很少需要这样做.我之所以仅提及它,是因为set.add
方法非常有用.
But there's rarely a need to do it this way. I only mention it because the set.add
method is quite useful.
这篇关于如何在python中构造一组列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!