Home > database >  Adding each item from one list to each item from another list to third list
Adding each item from one list to each item from another list to third list

Time:11-09

Image the following lists:

A = [1,2,3,4]
B = ['A','B','C','D']
C = [10,11,12,13]
D = [100,200,300,400]

I should get the following results: Z = ['1A10100', '2B11200', '3C12300', '4D13400']

I can do this using a lot of empty arrays, do it first using a for loop for A and B than use this new list and append C for each i, etc.

The question is, can this be done in a smarter way. In my real case the lists are 6?

CodePudding user response:

You can use a simple list comprehension:

Z = [''.join(str(x) for x in l) for l in zip(A,B,C,D)]

output: ['1A10100', '2B11200', '3C12300', '4D13400']

If you already have a container for your lists:

lists = [A,B,C,D]
[''.join(str(x) for x in l) for l in zip(*lists)]

CodePudding user response:

Using a list comprehension we can try:

A = [1,2,3,4]
B = ['A','B','C','D']
C = [10,11,12,13]
D = [100,200,300,400]

nums = list(range(0, len(A)))
Z = [str(A[i])   B[i]   str(C[i])   str(D[i]) for i in nums]
print(Z)  # ['1A10100', '2B11200', '3C12300', '4D13400']

CodePudding user response:

If the length of each lists are fixed and same length you can simply loop by indices, concatenate them, and then push altogether one-by-one into the result array.

A = [1,2,3,4]
B = ['A','B','C','D']
C = [10,11,12,13]
D = [100,200,300,400]

# Prepare the empty array
result = []

# Concat and insert one-by-one
for i in range(len(A)):
    result.append('{}{}{}{}'.format(A[i], B[i], C[i], D[i]))
    
print(result)

Output:

['1A10100', '2B11200', '3C12300', '4D13400']

There are also another way to concatenate and insert to the result array besides the code above:

  • You can assign a temporary variable to concatenate before inserting:
for i in range(len(A)):
    tmp = str(A[i])   B[i]   str(C[i])   str(D[i])
    result.append(tmp)
  • Or you can just put the variables in the inner curly brackets in this way
for i in range(len(A)):
    result.append(f'{A[i]}{B[i]}{C[i]}{D[i]}')
  • Related