英文:
How to create a dictionary from a list of strings with same key, value in python
问题
我有一个没有重复元素的字符串列表,我需要生成一个字典,其中这个列表的元素作为键,同时作为字典的值。
列表:
file_names = ['a', 'bb', 'ccc', 'ad', 'rsb']
期望的字典:
file_names = {'a': 'a', 'bb': 'bb', 'ccc': 'ccc', 'ad': 'ad', 'rsb': 'rsb'}
我希望列表的每个元素都作为键,并且确切地拥有该元素作为该键的值。在Python中,特别是Python 2中,生成这样一个字典的最快方式是什么?
英文:
I have a list of strings with no duplicate elements and I need to generate a dictionary with elements of this list as key and values of this dictionary.
List:
file_names = ['a', 'bb', 'ccc', 'ad', 'rsb']
Desired dictionary:
file_names = {'a': 'a', 'bb':'bb', 'ccc': 'ccc', 'ad': 'ad', 'rsb':'rsb'}
I want each element of list be as the key and also exactly have that element as it's value for that key. What is the best (most fast) way for generating such a dictionary in python specifically python 2?
答案1
得分: 4
请考虑使用 set
,如果您只想检查元素是否在集合中。这可以为成员测试提供 O(1)
复杂度。您可以通过以下方式将一个 list
转换为一个 set
:
file_names = set(['a', 'bb', 'ccc', 'ad', 'rsb'])
file_names = set(file_names)
然后,您可以通过以下方式简单地检查成员身份:
if file_name in file_names:
英文:
Please consider using a set
instead if all you wish to do is check if an element is in a collection. This gives you O(1)
complexity for membership tests. You can convert a list
to a set
by doing
file_names = set(['a', 'bb', 'ccc', 'ad', 'rsb'])
file_names = set(file_names)
Then, you can check for membership by simply doing
if file_name in file_names:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论