[英]How to create sublists out of a list with strings?
Having a Python list like the following one:有一个像下面这样的 Python 列表:
list1 = [ "abc", "def", "ghi" ]
How can I obtain sub-lists for each character of the strings ?如何获取字符串的每个字符的子列表?
list3 = [ ["a"], ["b"], ["c"] ]
list4 = [ ["d"], ["e"], ["f"] ]
list5 = [ ["g"], ["h"], ["i"] ]
Do not generate variables programmatically , this leads to unclear code and is often a source of bugs, use a container instead (dictionaries are ideal).不要以编程方式生成变量,这会导致代码不清楚并且通常是错误的来源,请改用容器(字典是理想的)。
Using a dictionary comprehension:使用字典理解:
list1 = [ "abc", "def", "ghi" ]
lists = {'list%s' % (i+3): [[e] for e in s]]
for i,s in enumerate(list1)}
output:输出:
>>> lists
{'list3': [['a'], ['b'], ['c']],
'list4': [['d'], ['e'], ['f']],
'list5': [['g'], ['h'], ['i']]}
>>> lists['list3']
[['a'], ['b'], ['c']]
NB.注意。 you could also simply use the number as key (3/4/5)
您也可以简单地使用数字作为键 (3/4/5)
To get a list
from a string use list(string)
要从字符串中获取
list
,请使用list(string)
list('hello') # -> ['h', 'e', 'l', 'l', 'o']
And if you want to wrap the individual characters in a list do it like this:如果您想将单个字符包装在列表中,请执行以下操作:
[list(c) for c in 'hello'] # --> [['h'], ['e'], ['l'], ['l'], ['o']]
But that is useful only if you want to change the list afterward.但这仅在您以后想更改列表时才有用。
Note that you can index a string like so请注意,您可以像这样索引字符串
'hello'[2] # --> 'l'
This is how to break a list then break it into character list.这是如何打破一个列表,然后将其分解为字符列表。
list1 = ["abc", "def", "ghi"]
list3 = list(list1[0])
list4 = list(list1[1])
list5 = list(list1[2])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.