Python: Combining two lists to make a new list - python

I would like to combine two lists in Python to make one list in the following way:
Input:
list1 = [a, b, c, d]
list2 = [1, 2, 3, 4]
Result should be:
list3 = [a1, a2, a3, a4, b1, b2, b3, b4, c1 ... ]

Or using list comprehension as a one liner, instead of nested loops:
list1 = ['a', 'b', 'c', 'd']
list2 = [1, 2, 3, 4]
list3 = [x + str(y) for x in list1 for y in list2]
Note: I assume you forgot the quotes in list1, and list3 is supposed to be a list of strings.

list1 = ['a','b','c','d']
list2 = [1,2,3,4]
list3 = []
for letter in list1:
for number in list2:
newElement = letter+str(number)
list3.append(newElement)
print list3
returns this:
['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4', 'd1', 'd2', 'd3', 'd4']

Related

Append lists to list of lists

I want to append lists of dataframes in an existing list of lists:
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']},
index=[0, 1, 2, 3])
fr_list = [[] for x in range(2)]
fr_list[0].append(df1)
fr_list[0].append(df1)
fr_list[1].append(df1)
fr2 = [[] for x in range(2)]
fr2[0].append(df1)
fr2[1].append(df1)
fr_list.append(fr2) # <-- here is the problem
Output: fr_list = [[df1, df1], [df1], [fr2[0], fr2[1]]] List contains 3 elements
Expected: fr_list = [[df1, df1, fr2[0]],[df1, fr2[1]]] List contains 2 elements
fr_list=[a+b for a,b in zip(fr_list,fr2)]
Replace fr_list.append(fr2) with the above code
Explanation: using zip & list comprehension, add corresponding lists in fr_list & fr2. What you did was appended the outer list in fr_list with outer list in fr & not the inner lists.

Cartesian product of two lists in python letters and numbers [duplicate]

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 3 years ago.
current
list1 = ['A','B','C']
list2 = [1,2,3]
Desired
list 3 = [['A', 1], ['A', 2], ['A', 3], ['B', 1], ['B', 2],['B', 3],
['C', 1], ['C', 2], ['C', 3]]
What I have tried
list3 = [l+str(n) for l in list1 for n in list2]
results in:
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
You were close:
[[l,n] for l in list1 for n in list2]
[[l]+[n] for l in list1 for n in list2]
As Mark has already mentioned, itertools.product would be the way to go. But if you want to continue to use a list comprehension, the correct line would be
list3 = [ [l, str(n)] for l in list1 for n in list2 ]

Compare nested list values within columns of a dataframe

How can I compare lists within two columns of a dataframe and identify if the elements of one list is within the other list and create another column with the missing elements.
The dataframe looks something like this:
df = pd.DataFrame({'A': ['a1', 'a2', 'a3'],
'B': [['b1', 'b2'], ['b1', 'b2', 'b3'], ['b2']],
'C': [['c1', 'b1'], ['b3'], ['b2', 'b1']],
'D': ['d1', 'd2', 'd3']})
I want to compare if elements of column C are in column B and output the missing values to column E, the desired output is:
df = pd.DataFrame({'A': ['a1', 'a2', 'a3'],
'B': [['b1', 'b2'], ['b1', 'b2', 'b3'], ['b2']],
'C': [['c1', 'b1'], ['b3'], ['b2', 'b1']],
'D': ['d1', 'd2', 'd3']
'E': ['b2', ['b1','b2'],'']})
Like your previous related question, you can use a list comprehension. As a general rule, you shouldn't force multiple different types of output, e.g. list or str, depending on result. Therefore, I have chosen lists throughout in this solution.
df['E'] = [list(set(x) - set(y)) for x, y in zip(df['B'], df['C'])]
print(df)
A B C D E
0 a1 [b1, b2] [c1, b1] d1 [b2]
1 a2 [b1, b2, b3] [b3] d2 [b1, b2]
2 a3 [b2] [b2, b1] d3 []
def Desintersection(i):
Output = [b for b in df['B'][i] if b not in df['C'][i]]
if(len(Output) == 0):
return ''
elif(len(Output) == 1):
return Output[0]
else:
return Output
df['E'] = df.index.map(Desintersection)
df
Like what I do for my previous answer
(df.B.map(set)-df.C.map(set)).map(list)
Out[112]:
0 [b2]
1 [b2, b1]
2 []
dtype: object
I agree with #jpp that you shouldn't mix the types so much, as when you try to apply the same function to the new E column, it will fail, cause it expected each element to be a list.
This would work on E, as it converts single str values to [str] before comparison.
import pandas as pd
df = pd.DataFrame({'A': ['a1', 'a2', 'a3'],
'B': [['b1', 'b2'], ['b1', 'b2', 'b3'], ['b2']],
'C': [['c1', 'b1'], ['b3'], ['b2', 'b1']],
'D': ['d1', 'd2', 'd3']})
def difference(df, A, B):
elements_to_list = lambda x: [n if isinstance(n, list) else [n] for n in x]
diff = [list(set(a).difference(set(b))) for a, b in zip(elements_to_list(df[A]), elements_to_list(df[B]))]
diff = [d if d else "" for d in diff] # replace empty lists with empty strings
return [d if len(d) != 1 else d[0] for d in diff] # return with single values extracted from the list
df['E'] = difference(df, "B", "C")
df['F'] = difference(df, "B", "E")
print(list(df['E']))
print(list(df['F']))
['b2', ['b2', 'b1'], '']
['b1', 'b3', 'b2']

Python: How can I manipulate csv data in a list?

I have created a list which has the totality of all the data in the csv file.
How do I seperately call upon data in rows and columns?
For instance:
**a, b ,c**
**1** a1 b1 c1
**2** a2 b2 c2
How can I identify a single cell within the list?
try below code:
l = ['a', 'b', 'c','1','a1', 'b1', 'c1', '2', 'a2', 'b2','c2']
columns = 3
result = list(zip(*[iter(l[columns:])]*(columns+1)))
result2 = {i[0]:i[1:] for i in result}
item_id = '2'
result2[item_id]
output:
('a2', 'b2', 'c2')
or you could try below code:
l = ['a', 'b', 'c','1','a1', 'b1', 'c1', '2', 'a2', 'b2','c2']
columns = 3
item_id = '2'
index = l.index(item_id)
l[index:index+columns]
output:
['a2', 'b2', 'c2']

Duplicating and Inserting into Nested List Python

I currently have nested list:
A = [[a1, a2, a3], c1, [a4, a5, a6], c2]
I also have another list:
B = [b1, b2]
I wish to duplicate A by the number of elements in B and then insert list B in the following way:
AB = [[a1, a2, a3], b1, c1, [a4, a5, a6], b1, c2, [a1, a2, a3], b2, c1, [a4, a5, a6], b2, c2]
The duplication I have managed to figure out easily:
AB = A * len(B)
However, the inserting of a list into a nested list has me completely stumped.
I'm currently using Python 3.6.1 and the size of list A and B can change but are always in the format of:
A template = [[x1, x2, x3], z1 ...]
B template = [y1, ...]
Any assistance will be greatly appreciated.
You can do it in a simple manner.
A = [['a1', 'a2', 'a3'], 'c1', ['a4', 'a5', 'a6'], 'c2']
AB=[]
B = ['b1', 'b2']
for i in B:
for j in A:
if isinstance(j,list):
AB.append(j)
else:
AB.append(i)
AB.append(j)
print AB
Output:[['a1', 'a2', 'a3'], 'b1', 'c1', ['a4', 'a5', 'a6'], 'b1', 'c2', ['a1', 'a2', 'a3'], 'b2', 'c1', ['a4', 'a5', 'a6'], 'b2', 'c2']

Categories

Resources