2

I go two lists of alphabets

headerListOne=['a', 'c', 'g', 'w', 'Q']

and another list

headerListTwo=['a', 'c', 'w', 'Q', 'front', 'Z']

and two lists of lists of numbers:

listToCompare=[[9, 0, 2, 7, 0]]
listToCompareTwo=[[0, 0, 0, 0, 3, 5]]

I want to get an output of:

 listToCompare=[[9,a,] [0,c] [2,g] [7,w] [0,Q]]
 listToCompareTwo=[[0,a], [0,c],[0,w], [0,Q], [3,front] [5,z]]

Basically I need to reference each number with an alphabet.Tuples are possible too but I prefer list methods because I'm more familiar with them.

Sook Yee Lim
  • 101
  • 1
  • 9
  • 4
    Use [`zip`](https://docs.python.org/3/library/functions.html#zip) – Patrick Haugh Oct 02 '17 at 16:42
  • Possible duplicate of [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) – pjpj Oct 02 '17 at 16:46

3 Answers3

1

You can try this:

headerListOne=['a', 'c', 'g', 'w', 'Q']
headerListTwo=['a', 'c', 'w', 'Q', 'front', 'Z']
listToCompare=[[9, 0, 2, 7, 0]]
listToCompareTwo=[[0, 0, 0, 0, 3, 5]] 
listToCompare = [[a, b] for a, b in zip(listToCompare[0], headerListOne)]
listToCompareTwo = [[a, b] for a, b in zip(listToCompareTwo[0], headerListTwo)]

Output:

[[9, 'a'], [0, 'c'], [2, 'g'], [7, 'w'], [0, 'Q']]
[[0, 'a'], [0, 'c'], [0, 'w'], [0, 'Q'], [3, 'front'], [5, 'Z']]

Edit:

if you have nested lists, you can try this:

listToCompareTwo=[[0, 0, 0, 0, 3, 5],[1,2,3,4,5,6]]
headerListTwo=['a', 'c', 'w', 'Q', 'front', 'Z']
final_list = [[[a, b] for a, b in zip(i, headerListTwo)] for i in listToCompareTwo]

Output:

[[[0, 'a'], [0, 'c'], [0, 'w'], [0, 'Q'], [3, 'front'], [5, 'Z']], [[1, 'a'], [2, 'c'], [3, 'w'], [4, 'Q'], [5, 'front'], [6, 'Z']]]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • It works thanks!But it only works if the list of list has one item.Say if listToCompareTwo=[[0, 0, 0, 0, 3, 5],[1,2,3,4,5,6]] it only inserts the alphabets in the first item?How do I make it work for all lists in listToCompareTwo? – Sook Yee Lim Oct 03 '17 at 09:59
0

Basically we want to combine two lists for which we can use map function. The command would be the following:

map(listToCompare, zip(headerListOne, listToCompare))

So the output would be:

listToCompare=[[9, a], [0, c], [2, g], [7, w] [0, Q]]
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
DZ1
  • 64
  • 1
0

so I did it only for the first line you just need to change some small stuff to do the second line but here it is:

if len(headerListOne) is len(listToCompare):
    for idx, val in enumerate(headerListOne):
        listToCompare[idx]=[listToCompare[idx], val]
Fe3back
  • 924
  • 7
  • 15