如何在python中从2D列表比较和打印元素?

时间:2018-10-03 22:12:39

标签: python list loops max min

我有这个2D列表,其中第一个元素是公司名称,第二个元素是高级开发人员的薪水多少,第三个元素是他们每周工作多少小时。

brands = [["Microsoft", "120", "38", "1124"], ["Apple", "150", "40", "1800"], ["Google", "110", "35", "1437"]]

我正在尝试比较brands[0][1] with brand[1][1] and brands [2][1]并打印行业中最低和最高的工资,例如"The lowest wage: Google, 110" "The highest wage: Apple,150",然后打印最低和最高的工作时间,对于简短列表,使用if和else语句很容易,但是如果列表更大,我将尝试建立一个通用循环。

我尝试了min(),但未成功,但是我确定有办法使它工作。

4 个答案:

答案 0 :(得分:3)

我将对您的列表进行排序,然后选择第一个和最后一个元素。您可以将其放在select month,count(1) as app_number from ( select month,app_id,supplier_reached,platform from your_table group by 1,2,3,4 ) group by 1 中进行打印(如果使用python 3.6或更高版本):

f-string

答案 1 :(得分:1)

也许这会起作用:

wage=[]
for var in range(len(brands)):
   wage.append(brands[var][1])

min=wage.index(min(wage))
print("The lowest wage :{0}, {1}".format(brands[min][0],brands[min][1])

答案 2 :(得分:1)

您可以将 lambda lambda 按所需的类别key=lambda x: x[1]进行分类,将参考工资,然后打印list[0][0], list[0][x]的相应索引list[-1][0], list[-1][x]代表我们的高点

wage = sorted(brands, key=lambda x: x[1])
print('The lowest wage: {}, {}'.format(wage[0][0], wage[0][1]))
print('The highest wage: {}, {}'.format(wage[-1][0], wage[-1][1]))

hours = (sorted(brands, key=lambda x: x[2]))
print('The lowest working hours: {}, {}'.format(hours[0][0], hours[0][2]))
print('The highest working hours: {}, {}'.format(hours[-1][0], hours[-1][2]))
The lowest wage: Google, 110
The highest wage: Apple, 150
The lowest working hours: Google, 35
The highest working hours: Apple, 40

答案 3 :(得分:0)

company = None
minwage = None

for brand in brands:
    if minwage is None or brand[1] < minwage:
        minwage = brand[1]
        company = brand[0]

print 'Lowest wage was: %s,%s' % (minwage, company)