Home > OS >  Combining elements of two lists based on the indexes of two separate lists in python
Combining elements of two lists based on the indexes of two separate lists in python

Time:12-23

I have four lists in python, lets call them A, Ai, B, and Bi

A and B are lists of numbers

Ai and Bi are lists of strings whose position in the lists corresponds to the number in the same position of the list with the same letter

eg.

A = [3, 4, 2]

B = [2, 7, 6]

Ai = ["Joe", "John", "Jim"]

Bi = ["John", "Jim", "Joe"]

(Joe is associated with 3 and 6 (in A and B respectively), for example)

I need a way to combine Joe's numbers for example, and have a way to know that that combination is joe's number.

Ideally, I would have a sorted list, each containing the combined numbers of A and B for each string in Ai or Bi (They will be the same strings), and a second list with the strings such that each string matches up to the number (in terms of index).

I have tried creating an association list for A and B (associating the strings with the numbers), and combining them in some way but failed.

CodePudding user response:

out = pd.concat([pd.Series(A, index=Ai), pd.Series(B, index=Bi)], keys=['A', 'B'], axis=1)

out

        A   B
Joe     3   6
John    4   2
Jim     2   7

CodePudding user response:

Following way your merge this four lists, by first create two dict and last merging them.

Code:

dic=dict(zip(Ai, [[i] for i in A]))
{dic[k].append(dict(zip(Bi, B))[k]) for k,v in dic.items()}
dic

Output:

{'Joe': [3, 6], 'John': [4, 2], 'Jim': [2, 7]}

CodePudding user response:

I want to try to help, but since I'm still new, I'm using javascript. ^_^

A = [3, 4, 2];
B = [2, 7, 6];

Ai = ["Joe", "John", "Jim"];
Bi = ["John", "Jim", "Joe"];

for (let i = 0; i < Ai.length; i  ) {
  for (let j = 0; j < Bi.length; j  ) {
    if (Ai[i] == Bi[j]) {
      let result = Ai[i]   ', ('   A[i]   ', '   B[j]   '), '   (A[i]   B[j]);
      console.log(result);
    }
  }
}

the result is like

Joe, (3, 6), 9
John, (4, 2), 6
Jim, (2, 7), 9 
  • Related