'access List within List and check index for item changed in 2nd list
I am trying to get data from list within list
data1 = [['Once per day', '50 times per day', 'Once per week', 'Twice per day'], ['Serverless', 'Infrastructure as a Service', 'Hybrid Compute', 'Virtual Machine Scale Set']]
data2 = [['Twice per day', '50 times per day', 'Once per day', 'Once per week'], ['Virtual Machine Scale Set', 'Infrastructure as a Service', 'Hybrid Compute', 'Serverless']]
I am trying to check in which index the first item from data1 is in data2 for example
Sample Output
3
4
as "Once per day" first item from data1 is changed to index 3 in data2 and adding 1 to index
Solution 1:[1]
I would iterate over the length of data1[0] or data2[0] and compare the value of each element. If they are different then you have found your index.
data1 = [['Once per day', '50 times per day', 'Once per week', 'Twice per day'], ['Serverless', 'Infrastructure as a Service', 'Hybrid Compute', 'Virtual Machine Scale Set']]
data2 = [['Twice per day', '50 times per day', 'Once per day', 'Once per week'], ['Virtual Machine Scale Set', 'Infrastructure as a Service', 'Hybrid Compute', 'Serverless']]
d1 = data1[0]
d2 = data2[0]
for i in range(len(d1)):
if d1[i] != d2[i]
print(0,i)
break
Solution 2:[2]
Accessing a list within a list is done via successive square brackets like print data1[0][0] would return Once per day. The rest of the process would be done via for loops!
Solution 3:[3]
A short way to do it :
L = [(data2[i].index(data1[i][0] ) +1) for i in range(len(data1)) ]
print(L)
output :
[3, 4]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Zach Frank |
| Solution 3 | Ayyoub ESSADEQ |
