簡體   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