简体   繁体   中英

Python append to an string element in a list

I'm fairly new to python. I want to know how can you append to a string element in a list cumulatively ?

list = ['1','2','3','4']
list2 = ['a','b','c','d']

I want a new list like this:

list3 = ['1a', '1b', '1c', '1d']

I've been running circles for possible answers. Help is much appreciated, thanks !

Using list comprehension . Note that you need to turn the integer into a string via the str() function, then you can use string concatenation to combine list1[0] and every element in list2. Also note that list is a keyword in python, so it is not a good name for a variable.

>>> list1 = [1,2,3,4]
>>> list2 = ['a','b','c','d']
>>> list3 = [str(list1[0]) + char for char in list2]
>>> list3
['1a', '1b', '1c', '1d']

You can use map() and zip like so:

list = ['1','2','3','4']
list2 = ['a','b','c','d'] 

print map(lambda x: x[0] + x[1],zip(list,list2))

Output:

['1a', '2b', '3c', '4d']

Online Demo - https://repl.it/CaTY

In your question you want list3 = ['1a', '1b', '1c', '1d'] .

If you really want this: list3 = ['1a', '2b', '3c', '4d'] then:

>>> list = ['1','2','3','4']
>>> list2 = ['a','b','c','d'] 
>>> zip(list, list2)
[('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd')]
>>> l3 = zip(list, list2)
>>> l4 = [x[0]+x[1] for x in l3]
>>> l4
['1a', '2b', '3c', '4d']
>>> 

I'm assuming your goal is [ '1a', '2b', '3c', '4d' ] ?

list = [ '1', '2', '3', '4' ]
list2 = [ 'a', 'b', 'c', 'd' ]
list3 = []

for i in range (len(list)):
    elem = list[i] + list2[i]
    list3 += [ elem ]

print list3

In general though, I'd be careful about doing this. There's no check here that the lists are the same length, so if list is longer than list2, you'd get an error, and if list is shorter than list2, you'd miss information.

I would do this specific problem like this:

letters = [ 'a', 'b', 'c', 'd' ]
numberedLetters = []

for i in range (len(letters)):
    numberedLetters += [ str(i+1) + letters[ i ] ]

print numberedLetters

And agree with the other posters, don't name your variable 'list' - not only because it's a keyword, but because variable names should be as informative as reasonably possible.

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