有什么方法可以改变列表对元素排序的方式吗?

2024-06-01 22:44:07 发布

您现在位置:Python中文网/ 问答频道 /正文

*所以基本上我创建了这个程序来计算当前西班牙语系统中的车牌数量,让用户引入一个特定的车牌号码(顺便说一下,它由4个数字和3个字母组成),程序打印它在系统中的位置,最后,在系统结束之前,该车牌还有多少剩余(最后一个是9999 ZZZ)

 consonant_letters = ['B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S',   
    'T', 'V', 'W', 'X', 'Y', 'Z']
    list_of_plates = []
    for x in range(10000):
        if x < 1000 and x > 99:
            x = f"0{x}"
        elif x < 100 and x > 9:
            x = f"00{x}"
        elif x < 10:
            x = f"000{x}"
        for y in consonant_letters:
            for z in consonant_letters:
                for a in consonant_letters:
                    list1 = f'{x} {y}{z}{a}'
                    list_of_plates.append(list1)

    print(list_of_plates)


    license_plate_user = input("Write the license plate: ")
    if license_plate_user in list_of_plates:
        print(list_of_plates.index(license_plate_user))
        license_plates_left = len(list_of_plates) - list_of_plates.index(license_plate_user)
        print(f'There are {license_plates_left} license plates left')
    else:
        print("Wrong values")

车牌的理想顺序是0000 BBB(这是第一个,因为我们不使用元音),下一个是0001 BBB,一旦达到9999,它就会变成0000 BBC,依此类推。(基本上是它们产生的顺序)。问题出现在我打印列表时,我看到它遵循某种模式,这显然违背了我程序的全部目的,因为位置数量和剩余车牌数量与实际情况不符。程序遵循的模式如下(这是最后几行代码,因为当有这么多数字时,在本例中为8000000,Python会删除前面几行):

ZWS', '9999 ZWT', '9999 ZWV', '9999 ZWW', '9999 ZWX', '9999 ZWY', '9999 ZWZ', '9999 ZXB', '9999 ZXC', '9999 ZXD', '9999 ZXF', '9999 ZXG', '9999 ZXH', '9999 ZXJ', '9999 ZXK', '9999 ZXL', '9999 ZXM', '9999 ZXN', '9999 ZXP', '9999 ZXR', '9999 ZXS', '9999 ZXT', '9999 ZXV', '9999 ZXW', '9999 ZXX', '9999 ZXY', '9999 ZXZ', '9999 ZYB', '9999 ZYC', '9999 ZYD', '9999 ZYF', '9999 ZYG', '9999 ZYH', '9999 ZYJ', '9999 ZYK', '9999 ZYL', '9999 ZYM', '9999 ZYN', '9999 ZYP', '9999 ZYR', '9999 ZYS', '9999 ZYT', '9999 ZYV', '9999 ZYW', '9999 ZYX', '9999 ZYY', '9999 ZYZ', '9999 ZZB', '9999 ZZC', '9999 ZZD', '9999 ZZF', '9999 ZZG', '9999 ZZH', '9999 ZZJ', '9999 ZZK', '9999 ZZL', '9999 ZZM', '9999 ZZN', '9999 ZZP', '9999 ZZR', '9999 ZZS', '9999 ZZT', '9999 ZZV', '9999 ZZW', '9999 ZZX', '9999 ZZY', '9999 ZZZ']

当代码的最后几行应该以从0000 ZZZ到9999 ZZZ的正确顺序排列时。 提前谢谢


Tags: ofin程序forlicense系统listprint
1条回答
网友
1楼 · 发布于 2024-06-01 22:44:07

由于数字在结转至字母之前先递增,因此应在字母循环中进行数字循环:

for y in consonant_letters:
    for z in consonant_letters:
        for a in consonant_letters:
            for x in range(10000):
                if x < 1000 and x > 99:
                    x = f"0{x}"
                elif x < 100 and x > 9:
                    x = f"00{x}"
                elif x < 10:
                    x = f"000{x}"
                list1 = f'{x} {y}{z}{a}'
                list_of_plates.append(list1)

您还可以使用itertools.product代替嵌套for循环,并使用f字符串而不是有条件地在零前加前缀:

from itertools import product
list_of_plates = [
    f'{n:04} {"".join(l)}'
    for l, n in product(product(consonant_letters, repeat=3), range(10000))
]

相关问题 更多 >