-1

I have to compare two lists of elements with the same length. (as an example [0,562,256,0,0,856] and [265,0,265,0,874,958]. Both list have an amount of zeroes and an amount of numbers above 249. I want to compare these lists. If at an index both lists have a number different from 0 the number should be saved in a list. The result should be two lists with the same length with only numbers above 249 (in the example [256,856] and [265,958]). Thanks for your help!

4

2 回答 2

3

Use zip() to pair up the elements of each list:

listA = [0,562,256,0,0,856]
listB = [265,0,265,0,874,958]

combined = zip(listA, listB)
resultA = [a for a, b in combined if a and b]
resultB = [b for a, b in combined if a and b]

gives:

>>> resultA
[256, 856]
>>> resultB
[265, 958]

You could also first use filter() to remove all pairs where one or the other element is 0:

combined = filter(lambda (a, b): (a and b), zip(listA, listB))
resultA = [a for a, b in combined]
resultB = [b for a, b in combined]
于 2013-03-14T11:55:10.060 回答
0

maybe we will find a better way,but

list1 = [0,562,256,0,0,856]
list2 = [265,0,265,0,874,958]
rest1 = []
rest2 = []
result1 = []
result2 = []
for i in range(len(list1)):
if list1[i] and list2[i]:
    rest1.append(list1[i])
        rest2.append(list2[i])
for i in range(len(rest1)):
if rest1[i] >249 and rest2[i]>249:
        result1.append(rest1[i])
    result2.append(rest2[i])
print(result1,result1)
于 2013-03-14T11:59:50.490 回答