简体   繁体   English

将字符串列表拆分为单独的字符 Python

[英]Split a list of strings into their individual characters Python

Let's say I have a list:假设我有一个列表:

list = ['foo', 'bar', 'bak']

I want to split these strings into their characters so I can assign values to each character (IE f = 5, o = 15, and so on).我想将这些字符串拆分为它们的字符,以便我可以为每个字符分配值(即 f = 5、o = 15 等)。

How might I decompose these lists?我如何分解这些列表? I was thinking of turning each element into its own list, and referring to each element as an item of that list, but I am not sure how to go about doing that.我想把每个元素变成它自己的列表,并将每个元素称为该列表的一个项目,但我不知道如何去做。

Strings are iterable in Python, so you can just loop through them like this:字符串在 Python 中是可迭代的,所以你可以像这样循环遍历它们:

list = ['foo', 'bar', 'bak']

for item in list:
    for character in item:
        print(character)

If This Is What Your Looking For Here You Go:如果这就是您要找的东西,您可以:

listItems = ['foo', 'bar', 'bak']
listLetter = []
myDictionary = {}

for item in listItems:
    for letter in item:
        listLetter.append(letter)

myDictionary['f'] = 5

print myDictionary

Maybe that's what you want to convert into list of characters:也许这就是您想要转换为字符列表的内容:

l = ['foo', 'bar', 'bak']

list(''.join(l))

You can use one line solution :您可以使用一行解决方案:

list1 = ['foo', 'bar', 'bak']
print([j for i in list1 for j in i])

result :结果 :

['f', 'o', 'o', 'b', 'a', 'r', 'b', 'a', 'k']

Join the entire list to each character将整个列表加入每个字符

my_list = ['foo', 'bar', 'bak'] my_list = ['foo', 'bar', 'bak']

result = list(''.join(my_list))结果 = list(''.join(my_list))

result结果

['f', 'o', 'o', 'b', 'a', 'r', 'b', 'a', 'k'] ['f', 'o', 'o', 'b', 'a', 'r', 'b', 'a', 'k']

now you can iterate through result to assign value to each character现在您可以遍历结果为每个字符赋值

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

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