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

在Python中从字符串列表创建列表,python,Python,我有一个Python列表: ['first', 'second', 'foo'] 我想创建以列表元素命名的列表列表: newlist = ['first':[], 'second':[], 'foo':[]] 我见过一些使用字典的建议,但当我尝试使用OrderedICT时,我失去了创建中元素的顺序 提前感谢。由于已订购Python 3.7常规Python的dicts: >>> dict((name, []) for name in ['first', 'second', '

我有一个Python列表:

['first', 'second', 'foo']
我想创建以列表元素命名的列表列表:

newlist = ['first':[], 'second':[], 'foo':[]]
我见过一些使用字典的建议,但当我尝试使用OrderedICT时,我失去了创建中元素的顺序


提前感谢。

由于已订购Python 3.7常规Python的
dict
s:

>>> 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])

数组中的元素必须是适当的对象,并且示例中显示的格式没有多大意义,但是您可以尝试在数组中使用
字典
元素,其中每个元素都有键(即
'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': []}

您可以使用方法
fromkeys()

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

from collections import OrderedDict

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

第一个问题是您提到术语“list”,但您指的是一个单词概念,而不是Python语言中的数据类型。第二个问题是,结果将不再表示数据类型
,而是表示
(字典)的数据类型。对于
,一行简单的
,可以将变量类型
转换为所需的字典类型变量。它在Python2.7.x中工作

>>> l = ['first', 'second', 'foo']
>>> type(l)
<type 'list'>
>>> d = {x:[] for x in l}
>>> type(d)
<type 'dict'>
>>> d
{'second': [], 'foo': [], 'first': []}
>l=['first','second','foo']
>>>类型(l)
>>>d={x:[]表示l}中的x
>>>类型(d)
>>>d
{'second':[],'foo':[],'first':[]

您使用的是哪一版本的python?版本2.7.14。如果您希望某个东西(如
'first'
)与某个东西(如列表)相关联,则可以使用键值对。这些通常被实现为
dict
{'first':[],'second':[]}
),但是如果你真的想要一个列表,那么我推荐一个
元组的列表(
[('first',[]),('second',[])
。你是如何创建
有序的dict
。它的唯一目的是保留插入元素的顺序。我声明:newlist=collections.OrderedDict()和更高版本:used newlist={I:[]for I in signal_list}。我得到了{'second':[],'foo':[],'first':[]}(即不同的顺序),这一个创建了[('first',[]),('second',[]),('third',[])。不是我想要的不,这一个创建了
orderedict([('first',[]),('second',[]),('foo',[])))
。这是一个OrderedDict对象,而不是列表,请不要混淆它们。
{name:[]对于['first'、'second'、'third']]中的name来说
会自然得多。
>>> l = ['first', 'second', 'foo']
>>> type(l)
<type 'list'>
>>> d = {x:[] for x in l}
>>> type(d)
<type 'dict'>
>>> d
{'second': [], 'foo': [], 'first': []}