简体   繁体   中英

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

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:

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

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

result

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

now you can iterate through result to assign value to each character

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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