简体   繁体   English

向后打印元组

[英]Printing a tuple backwards

I am working on a piece of Python code that consists of allowing the user to enter the top speed for 3 different cars, then prints out the car's name and top speed sorted in ascending order. 我正在研究一段Python代码,其中包括允许用户为3种不同的汽车输入最高速度,然后打印出汽车的名称和最高速度按升序排序。

So far, two lists have been created 到目前为止,已经创建了两个列表

carName= ["Ferrari", "Lambo", "Porsche"]

and

carSpeed= ["245.5794", "242.4616", "318.1555"]

The carSpeed has been rounded to 2 decimal place with carSpeed已经四舍五入到小数点后两位

carSpeedTwoDP= ['%.2f' % elem for elem in carSpeed]

And that list, along with carName , has been made into a tuple 该列表与carName一起被制作成元组

carSpeedSorted= sorted(zip(carSpeed, carName))

I then print out the tuple with 然后我打印出元组

for i in range (3):
    print "%s"% (carSpeedSorted[i],)

This poses a problem however. 然而,这提出了一个问题。 The table is supposed to show 该表应该显示

Lambo 242.46
Ferrari 245.58
Porsche 318.16

But because the speed is first in the tuple (as the list must be sorted in ascending speed order and tuples sort themselves with the first elements they can find), the display is the following: 但是因为速度是元组中的第一个(因为列表必须按升序速度排序,而元组使用它们可以找到的第一个元素对它们进行排序),显示如下:

('242.46', 'Lambo')
('245.58', 'Ferrari')
('318.16', 'Porsche ')

I have been researching for a while, but haven't been able to come up with a solution to invert the lists so that the car name shows up first, all the while keeping the tuple sorted by speed. 我已经研究了一段时间,但是还没有能够提出一个解决方案来反转列表,以便首先显示汽车名称,同时保持元组按速度排序。

Any help would be greatly appreciated! 任何帮助将不胜感激! Thank you! 谢谢!

You can simply put the car names first and sort using the second element of each tuple as the key: 您可以简单地将汽车名称放在第一位,并使用每个元组的第二个元素作为关键字进行排序:

from operator import itemgetter
carSpeedSorted = sorted(zip(carName, carSpeed), key=itemgetter(1))

And now: 现在:

for a in carSpeedSorted:
    print '%s' % (a,) 
('Lambo', '242.4616')
('Ferrari', '245.5794')
('Porsche', '318.1555')

References: 参考文献:

What happened to the reversed slice operator? 反转切片操作符发生了什么变化?

print (0, 1, 2)[::-1]
# Outputs '(2, 1, 0)'

This is known as 'Reverse Slicing'. 这被称为“反向切片”。 It's minimal, but it works in anything that is pretty much a sequence, or contains multiples of an item, such as a tuple or a list . 它是最小的,但它适用于任何几乎是序列的东西,或者包含多个项目,例如tuplelist You can read more about reversal here . 您可以在此处阅读有关逆转的更多信息。

There are two solutions to your problem. 您的问题有两种解决方案。

1. Fix printing 1.修复打印

There are ways to do that: 有办法做到这一点:

carSpeedSorted[i] = ('242.46', 'Lambo')

print "{1} {0}".format(*carSpeedSorted[i])

# or:
print "%s %s" % (carSpeedSorted[i][1], carSpeedSorted[i][0])

# or:
speed, name = carSpeedSorted[i]
print "%s %s" % (name, speed)

# or:
print "%(name)s %(speed)s" % dict(speed=carSpeedSorted[i][0], 
                                  name=carSpeedSorted[i][1])

2. Fix sorting 2.修复排序

You can have (name, speed) tuples and still sort by speed, eg: 您可以拥有(name, speed)元组并仍按速度排序,例如:

sorted(name_speed_tuples, key=lambda name_speed: name_speed[1])

BTW, are sure you want to sort by speed alphabeticaly ? 顺便说一下,你确定要按字母顺序排序吗?

In your code, speed '1000.00' will come before '200.00'! 在您的代码中,速度'1000.00'将在'200.00'之前出现!

I suggest using round for rounding the numbers, instead of creating a string. 我建议使用round来舍入数字,而不是创建一个字符串。 That would fix the problem. 那样可以解决问题。

carSpeedTwoDP= [round(elem,2) for elem in carSpeed]

Actually you can very easily sort by second elements of tuples: 实际上你可以很容易地按元组的第二个元素排序:

sorted(zip(carName, carSpeed), key=lambda x: (x[1], x[0]))

The above method sorts the list of tuples in ascending order of their speeds, and in case of a draw, the one with smaller name comes first. 上面的方法按照它们的速度的升序对元组列表进行排序,并且在绘制的情况下,名字较小的元组首先出现。

Why not just print it in the required order? 为什么不按要求的顺序打印?

print( "%s %s" %(carSpeedSorted[i][1],carSpeedSorted[i][0]))

OUTPUT OUTPUT

Lambo 242.4616
Ferrari 245.5794
Porsche 318.1555

Others correctly point out that you can sort without reversing the items in the first place, but if you want to print when the tuple is in the "wrong" order, it's not hard, just reverse the tuple (and make the format string print both parts): 其他人正确地指出你可以在不首先反转项目的情况下进行排序,但如果你想在tuple处于“错误”顺序时进行打印,那就不难了,只需反转tuple (并使格式字符串同时打印)部分):

# Iterate list directly; indexing on range is a C habit you should get out of
for carspeed in carSpeedSorted:
    # Reverse the tuple and use it directly; wrapping in a single element
    # tuple adds the parens and commas your desired output didn't want
    print "%s %s" % carspeed[::-1]

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

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