简体   繁体   English

比较嵌套列表推导中的数字

[英]compare numbers in Nested List Comprehensions

Can some one help me to compare numbers in nested list l=[[6, 6], [15, 24], [85, 18]] ;有人可以帮我比较嵌套列表中的数字l=[[6, 6], [15, 24], [85, 18]] for example:例如:

for i in l:
    if i[0][0]>i[0][1]:
        print("B")
    elif i[0][0]<i[0][1]:
        print("A")
    else:
        print("T")



Expected Output :
  T
  A
  B

  
    

You can try this:你可以试试这个:

l=[[6, 6], [23, 24], [85, 18]]

print(*['B' if i[0]>i[1] else ('A' if i[0]<i[1] else 'T')  for i in l], sep = "\n") 

Or if you want to use your original solution, just erase the i[0][0] because with the loop you are accesing to each list, so i is each nested list, eg [6, 6], [15, 24], [85, 18]或者,如果您想使用原始解决方案,只需删除i[0][0] ,因为使用循环您正在访问每个列表,所以i是每个嵌套列表,例如[6, 6], [15, 24], [85, 18]

l=[[6, 6], [15, 24], [85, 18]]
for i in l:
    if i[0]>i[1]:
        print("B")
    elif i[0]<i[1]:
        print("A")
    else:
        print("T")

Both outputs:两个输出:

T
A
B
    

Use meaningful variables to make your code more readable使用有意义的变量使您的代码更具可读性

for subarray in l:
    a,b = subarray
    if a > b:
        print("A")
    elif a < b:
        print("B")
    else:
        print("T")

You are accessing an array after entering the outer for loop so use index numbers as you would in a one dimensional array.您在进入外部 for 循环后访问数组,因此请像在一维数组中一样使用索引号。

for i in l:
  if i[0] > i[1]:
    print("B")
  elif i[0] < i[1]
    print("A")
  else
    print("T")

You can :可以

l = [[6, 6], [15, 24], [85, 18]]
out = ["B" if x > y else ("A" if x < y else "T") for x, y in l]
print(out)
# ['T', 'A', 'B']

Would I use it?我会用它吗? Not so sure but it really depends on your requirements.不太确定,但这确实取决于您的要求。

your_list = [[6, 6], [15, 24], [85, 18]]

def compare(ab):
    a,b = ab
    if a > b: return "B"
    if a < b: return "A"
    if a == b: return "T"
        
res = "\n".join(map(compare, your_list))
print(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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