【问题标题】:How to compare an element to another element , that is inside a nested list? (in python)如何将一个元素与嵌套列表中的另一个元素进行比较? (在蟒蛇中)
【发布时间】:2020-08-01 20:49:25
【问题描述】:

我得到了一个列表,其中包含另一个列表形式的一些学生的姓名和分数。

例如:lis=[['barry',35],['larry',20],['cathy',10],['mathew',10]]

我需要找到分数第二低的学生的姓名。对于上述输入,答案将是:cathey 马修

我尝试通过以下方式解决它。但是没有输出。 谁能找出我的代码中的错误?

x=int(input()) #total number of element
lis=[]         #list
pis=[]
for _ in range(x) :

    name = input()    
    score = float(input())
    lis.append([name,score]) #appending name and score to lis
    pis.append([score])       #appending only scores to pis
pis.sort()    #sorting pis
lis.sort()    #sorting lis

x=pis[1]      #finding the 2nd smallest score in pis

for i in lis:

    
    if ((i[1])) == x:  #comparing the second smallest number to every score in lis

        print (i[0])    #printing only  the name if the scores are same,(this step don't work)

【问题讨论】:

  • "pis" 也是一个列表列表(不必要)。所以“pis[1]”是一个列表。

标签: python python-3.x list logic out-of-memory


【解决方案1】:
x=int(input()) 
lis = [] 
for _ in range(x):
    name = input()    
    score = float(input())
    lis.append([name,score])

#changing list into a dict for sorting the data by its value. 
lis = dict(lis)

#using lambda function inside sorted() for targeting the value in dictionary to be sorted.
sort_orders = sorted(lis.items(), key=lambda x: x[1])

#used for loop here to only print first two key items of the dictionary sort_orders.
for i in range(2):
    print(sort_orders[i][0], end = " ")

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
  • 感谢您的建议,我将在以后的帖子中使用它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 2019-01-19
  • 2020-08-30
  • 2020-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多