简体   繁体   中英

Sorting a 3 parallel list that includes strings and numeric value in Python

how to sort using 3 parallel array lists:

num1 = ['a','b','c,']
num2 = ['apple','pear','grapes']
num3 = [2.5,4.0,.68]

I used 2 for statements followed by a if statement. Sorting by elements the output should be:

a apple 2.5
b pear 4.0
c grapes .68

unfortunately, I am having issues with sorting the 3rd num3 values using the element swapping sort. any ideas

Since you say the lists are parallel, let's group them into tuples, and then sort the list of tuples.

num1 = ['a','b','c']
num2 = ['apple','pear','grapes']
num3 = [2.5,4.0,.68]

lst = zip(num1, num2, num3)
lst.sort()

for x1, x2, x3 in lst:
    print x1, x2, x3,

print

The result is:

a apple 2.5 b pear 4.0 c grapes 0.68

From your desired inputs and output it doesn't seem you want any sorting -- just:

num1 = ['a','b','c']
num2 = ['apple','pear','grapes']
num3 = [2.5,4.0,.68]
for item in [x for t in zip(num1, num2, num3) for x in t]:
  print item,
print

This does give the output you mention -- is this what you want?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM