繁体   English   中英

在Python中从字符串列表创建列表

[英]Create a list from strings-list in Python

我在Python中有一个列表:

['first', 'second', 'foo']

我想创建一个以list元素命名的列表列表:

newlist = ['first':[], 'second':[], 'foo':[]]

我看到了一些使用字典的建议,但是当我尝试使用OrderedDict进行操作时,我丢失了创建中元素的顺序。

提前致谢。

您可以使用fromkeys()方法:

l = ['first', 'second', 'foo']

dict.fromkeys(l, [])
# {'first': [], 'second': [], 'foo': []}

在Python 3.6及以下版本中,请使用OrderedDict而不是dict

from collections import OrderedDict

l = ['first', 'second', 'foo']
OrderedDict.fromkeys(l, [])
# OrderedDict([('first', []), ('second', []), ('foo', [])])

由于Python 3.7常规Python的dict是有序的:

>>> dict((name, []) for name in ['first', 'second', 'third'])
{'first': [], 'second': [], 'third': []}

CPython 3.6中的dict也是有序的,但这是一个实现细节。

@ForceBru对于Python 3.7(我了解到自己)给出了一个很好的答案,但是对于可以使用的较低版本:

from collections import OrderedDict
l = ['first', 'second', 'foo']
d = OrderedDict([(x, []) for x in l])

您最终想要拥有的数组中的元素必须是正确的对象,并且您在示例中显示的格式没有多大意义,但是您可以尝试在数组中使用dictionary元素,其中每个元素都有键(ei'foo 'foo' )和值(即'[]' )。 因此,您将得到如下所示的结果:

newlist = [{'first':[]}, {'second':[]}, {'foo':[]}]

现在,如果您对此感到满意,这是一个带有匿名lambda函数的map函数,它将转换您的初始数组:

simplelist = ['first', 'second', 'foo']
newlist = list(map(lambda item: {item:[]}, simplelist))

希望,你得到了答案。

干杯!

您指定的结构是字典dict 结构如下:

test_dictionary = {'a':1, 'b':2, 'c':3}

# To access an element
print(test_dictionary['a'])   # Prints 1

根据您的要求创建字典:

test_dictionary = dict((name, []) for name in ['first', 'second', 'foo'])
print(test_dictionary)

上面的代码行给出以下输出:

{'first': [], 'second': [], 'foo': []}

第一个问题是您指的是“列表”一词,但您将其表示为单词概念,而不是Python语言中的数据类型。 第二个问题是结果将不再代表数据类型<list> ,而是代表<dict> (字典)的数据类型。 一个简单的一个线for可以将可变类型的转换<list>到所需的字典式可变。 它适用于Python 2.7.x

>>> l = ['first', 'second', 'foo']
>>> type(l)
<type 'list'>
>>> d = {x:[] for x in l}
>>> type(d)
<type 'dict'>
>>> d
{'second': [], 'foo': [], 'first': []}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM