简体   繁体   中英

Join lists of different lengths at unequal intervals in python?

I'm trying to join two lists that have different lengths of data.

list1 = [a,b,c,d,e,f]
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

My desired out put would be something like this:

[a12, b34, c56, d78, e910, f1112

My first though would be to do something like increment i at different intervals

for i in printlist:
    for i in stats:
        print(printlist[i] + stats[i] + stats[i+1])

But that spits out TypeError: list indices must be integers or slices, not str and I don't see that working since i would increment incorrectly for both lists.

Any help would be appreciated

Try this,

list1 = ["a","b","c","d","e","f"]
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

list3 = [str(i)+str(j) for i,j in zip(list2[::2], list2[1::2])]
["".join(list(x)) for x in zip(list1, list3)]

output

['a12', 'b34', 'c56', 'd78', 'e910', 'f1112']

A simple way to code it is to have 2 counters to keep track of indices. One you increment by 1 on each iteration, and the other by 2 on each iteration. This would be done as follows:

list1 = ['a','b','c','d','e','f']
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

list3 = []
i = 0
j = 0
while i < len(list1):
  list3.append(list1[i] + str(list2[j]) + str(list2[j+1]))
  i += 1
  j += 2

print(list3)

But you'll notice that j here is always twice the value of i (ie j=2*i ) so there's no point having 2 counters. So you can simplify it this way:

list1 = ['a','b','c','d','e','f']
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

list3 = []
for i in range(0, len(list1)):
  list3.append(list1[i] + str(list2[2*i]) + str(list2[2*i + 1]))

print(list3)

or as list comprehension:

list1 = ['a','b','c','d','e','f']
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

list3 = [list1[i] + str(list2[2*i]) + str(list2[2*i + 1]) for i in range(0, len(list1))]
print(list3)

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