如何通过第二个值在嵌套列表中找到第二低的列表?

问题描述 投票:0回答:12

这里给出一个嵌套列表:

nl = [['Harsh', 20], ['Beria', 20], ['Varun', 19], ['Kakunami', 19], ['Vikas', 21]]

现在我必须通过第二个值在嵌套列表中找到第二低的列表。并将第二低的列表附加到另一个列表中。

所以输出应该是:

['Harsh', 20], ['Beria', 20]

我编写了以下代码,但它不起作用:

nl = [['Harsh', 20], ['Beria', 20], ['Varun', 19], ['Kakunami', 19], ['Vikas', 21]]

result=[]

temp=max(nl, key=lambda x: x[1])

largest, larger = temp[1], temp[1]
for num in nl:
    if num[1] < largest:
        largest, larger = num[1], largest
    elif num[1] < larger:
        larger = num[1]
        result.append(larger)
print(result)
python list python-3.x nested-lists
12个回答
9
投票

获取总元素的

min
,使用该有效值进行过滤,然后获取剩余的最小值,并保持元素等于剩余的最小值:

from operator import itemgetter
# min of all elements
mn = min(nl, key=itemgetter(1))[1]

# remove elements equal to min
filtered = [x for x in nl if x[1] != mn]

# get min of remaining
mn_fil = min(filtered,key=itemgetter(1))[1]

# filter remaining
out = [x for x in filtered if x[1] == mn_fil]
print(out)

[['Harsh', 20], ['Beria', 20]]

适用于您的两种情况:

In [19]: nl = [['Prashant', 32], ['Pallavi', 36], ['Dheeraj', 39], ['Shivam', 40]]    
In [20]: from operator import itemgetter    
In [21]: mn = min(nl, key=itemgetter(1))[1]    
In [22]: filtered = [x for x in nl if x[1] != mn]    
In [23]: mn_fil = min(filtered,key=itemgetter(1))[1]    
In [24]: out = [x for x in filtered if x[1] == mn_fil]    
In [25]: out
Out[25]: [['Dheeraj', 36]]

使用单个 for 循环,如果找到较低的元素,则从临时列表中删除所有元素,如果找到同样较低的元素,则将其附加:

mn = min(nl, key=itemgetter(1))[1]
temp = []
best = float("inf")
for ele in nl:
    if mn < ele[1] < best:
        best = ele[1]
        temp = []
        out.append(ele)
    elif ele[1] == best:
        temp.append(ele)
print(temp)

1
投票

我通过使用集合查找第二低值,然后从列表中选择具有相同值的元素来做到这一点。

#ordering by value
nl.sort(key = lambda x: x[1])

values_set = set()
for value in nl:
    values_set.add(value[1])

values_list = list(values_set)
#ordering
values_list.sort()
#getting second lowest values
lowest_values = [lowest for lowest in nl if lowest[1] == values_list[1] ]

1
投票
if __name__ == '__main__':
arr = []
for _ in range(int(input())):
    name = input()
    score = float(input())
    arr1 = [name, score]
    arr.append(arr1)
arr.sort(key=lambda x: x[1])
# print(arr)
# print(min(arr,key=lambda x:x[1]))
arr.remove(min(arr,key=lambda x:x[1]))
# print(arr)
minimum = min(arr,key=lambda x:x[1])
# print(minimum[1])
a=[]
minimum = minimum[1]
for i  in arr:
    if(i[1] == minimum):
        a.append(i[0])
a.sort()
for i in a:
    print(i)

0
投票

这是一个方便的小功能,其中包含

heapq.nlargest

返回包含数据集中 n 个最大元素的列表


import heapq
num = heapq.nlargest(2, [key for item, key in nl])[-1]
print [item for item in nl if item[-1] == num] #[['Harsh', 20], ['Beria', 20]]

0
投票

您可以尝试下面的代码。效果很好。

lst=[['Harry',37.21],['Berry',37.21],['Tina',37.2],['Akriti',41],['Harsh',39]]
names=[]
lowest = lst[0].__getitem__(1)
second_lowest=0
for l in lst:
    if l[1] < lowest:
        second_lowest = lowest
        lowest = l[1]
    elif l[1]<=second_lowest:
        second_lowest=l[1]
for l in lst:
    if l[1]==second_lowest:
        names.append(l[0])


print(lowest)
print(second_lowest)
print(names)

0
投票
if __name__ == '__main__':

    n = []
    s = []
    for _ in range(int(input())):
        name = input()
        n.append(name)
        score = float(input())
        s.append(score)
        
data = [[x,y] for x,y in zip(n,s)]

min_marks = min([x[1] for x in data])

filtered_data = [d for d in data if d[1] != min_marks]

sec_min = min([x[1] for x in filtered_data])

students_with_sec_min_marks = sorted([d[0] for d in filtered_data if d[1] == sec_min])

for s in students_with_sec_min_marks:
    print(s)

0
投票
if __name__ == '__main__':
    lst = []
    names = []
    for _ in range(int(input())):
        name = input()
        score = float(input())
        lst.append([name, score])
     
    lowest = max(lst, key=lambda x: x[1])[1]
    second_lowest=0
    for l in lst:
        if l[1] < lowest:
            second_lowest = lowest
            lowest = l[1]
        elif l[1] < second_lowest and l[1] != lowest:
            second_lowest = l[1]
    for l in lst:
        if l[1] == second_lowest:
            names.append(l[0])  
    
    names.sort()
    for nm in names:
        print(nm)

0
投票

我使用了下面的代码,效果很好:

records = []

if __name__ == '__main__':
    for i in range(int(input())):
        name = input()
        score = float(input())
        records.append([name,score])
        records.sort(key=lambda x:x[1])
    minimum = min(records,key=lambda x:x[1])
    minimum = minimum[1]
    args = records.copy()
    
    for i in args:
        if(i[1] == minimum):
            records.remove(i)
        else:
            continue
    
    minimum = min(records,key=lambda x:x[1])
    minimum = minimum[1]
    a=[]
    for i  in records:
        if(i[1] == minimum):
            a.append(i[0])

    a.sort()
    for i in a:
        print(i)

这样,您还可以删除多个相同的最低分数(如果存在)。在没有

copy()
的情况下运行它并处理原始列表会导致循环错过几个相同的最低分数。


0
投票
students=[]
if __name__ == '__main__':
    for _ in range(int(input())):
        name = input()
        score = float(input())
        students.append([name,score])
    
            
students.sort(key=lambda x:x[1]  )  
students.remove(min(students,key=lambda x:x[1] ))
names=[]
score=students[0][1]
for student in students:
    if student[1]==score:
        names.append(student[0])
names.sort()
for each in names:
    print(each)

0
投票

我做了一个简单的方法来解决这个问题,它是基本的而不是进步的

if __name__ == '__main__':
records = []
for _ in range(int(input())):
    name = input()
    score = float(input())
    records.append([name,score])
    
sorted_records = sorted(records, key=lambda x: x[1])
second_lowest = 0
for item in sorted_records:
    if  sorted_records[0][1] < item[1]:
        second_lowest = item[1] 
        break
second_lowest_list = [x for x in sorted_records if second_lowest==x[1]]
second_lowest_list.sort()
for element in second_lowest_list:
   print(element[0])

-1
投票

您的示例可以简化为:

second_lowest = sorted(set(v[1] for v in nl))[1]
result = [v for v in nl if v[1] == second_lowest]
print(result) # [['Harsh', 20], ['Beria', 20]]

我使用您的一组值来查找第二个唯一的最低值。 比拥有这个文件,在 nl 中查找与找到的值匹配的元素。


-1
投票

我遇到过类似的问题,在参考此页面后,我得到了一些想法并能够解决它。

nl = [['Harsh', 20], ['Beria', 20], ['Varun', 19], ['Kakunami', 19], ['Vikas', 21]]

second = max(nl, key= lambda x: x[1])[1]
first = min(nl, key= lambda x: x[1])[1]
    
for i in range(len(nl)):
    if nl[i][1] <= second and nl[i][1] != first:
        second = nl[i][1]
    
for i in range(len(nl)):
    if second == nl[i][1]:
        print(nl[i], end=", ")
© www.soinside.com 2019 - 2024. All rights reserved.