I have two lists of strings that, in a better world, would be one list. I need to concatenate the lists, but the last element of the first list needs to be concatenated with the first element of the second list. So these guys:
list1 = ["bob", "sal"]
list2 = ["ly", "nigel"]
needs to become
out = ["bob", "sally", "nigel"]
So this isn't hard, but I'm wondering why my one liner doesn't work?
out = (list1[-1] += list2.pop(0)) += list2
Why isn't this equivalent to
out = list1[-1]+=list2.pop(0)
out += list2
?
I have to do this a large percentage of the time through some 400K records. So if anyone has a better way to do this, then I'd be grateful!
Remove all those +=
operators, they don't make sense here. If you want to use them as a replacement for a.extend(b)
, then remember, that they cannot be used as an expression. This command modifies the a
list, but does not return anything. So c = a.extend(b)
gives nothing to c
.
Try this instead (it even does not modify original lists!):
out = list1[:-1] + [ list1[-1] + list2[0] ] + list2[1:]
returns what you want.
list1[:-1]
is a list from list1 without the last element. list1[-1]
is the last element from list1. list2[0]
is the first element from list2. list1[-1] + list2[0]
is a concatenated string. [ list1[-1] + list2[0] ]
is a list with one element (concatenated string). list2[1:]
is a list from list2 without the first element. Assignments in Python are not operators that can be used within expressions. They are statement-level syntax.
如果您想要单线飞机,这是我要做的:
(','.join(list1)+','.join(list2)).split(',')
Apart of @eumiros answer, on what is happening there, you can acomplish what you want in a single statement with:
out = list1[:-1] + [list1[-1] + list2[0]] + list2[1:]
"There should be one-- and preferably only one --obvious way to do it."
I would not normally leave broken pieces of data around but would fix in place:
>>> list1 = ["bob", "sal"]
>>> list2 = ["ly", "nigel"]
>>> fix = [list1.pop()+list2.pop(0)]
>>> list1
['bob']
>>> fix
['sally']
>>> list2
['nigel']
>>> fixed = list1 + fix + list2
>>> fixed
['bob', 'sally', 'nigel']
Same time getting rid of those obvious list1 and list2 variable names with something readable.
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.