如何在python中将字母与10的倍数配对(0A9A然后0B….)

2024-04-27 02:29:29 发布

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

我正在尝试创建一个程序,通过给列表中的项目一个从0到9的数字,后跟一个字母来标识它们。它的工作原理是这样的:前10个项目是0A,1A,2A,一直到9A。然后我想把第11个项目变成0B。有没有办法让python自动做到这一点?我将举一个产品列表的例子,这些产品需要一个ID来回答问题。你知道吗

import random
import string

alphabet= "ABCDEFGHIJKLMOPQRSTUVWYZ"
products_fruit = ["apple", "banana", "orange", "grapes"]
fruit_id = range(0, len(products_fruit))

for id, product in zip(fruit_id, products_fruit):
  print("0" + str(id) + str(alphabet[0]) + " =", product)

你可以看到,现在我只是打印一个A,但我想我的第11个项目自动有str(字母表[1])(字母B)打印后是0B。 此代码的结果是:

00A = apple
01A = banana
02A = orange
03A = grapes

我希望第11个和第21个产品是: 00B=产品11 00C=产品21

谢谢你!你知道吗


Tags: 项目importidapple列表产品字母product
3条回答

按以下方式更改for循环:

for id, product in zip(fruit_id, products_fruit):
  print("0" + str(id%10) + str(alphabet[id//10]) + " =", product)

尝试:

alphabet = "ABCDEFGHIJKLMOPQRSTUVWYZ"
products_fruit = ["apple", "banana", "orange", "grapes"]

for idx, product in enumerate(products_fruit):
    if idx >= len(alphabet) * 10:
        raise ValueError("products_fruit contains too many entries")

    ch = alphabet[idx // 10]
    no = idx % 10
    print('0', str(no), ch, ' = ', product, sep='')

实现这一点的标准方法是itertools.product,它可以作为排序的“multi-for-loop”。你知道吗

import itertools
import string

for letter, number in itertools.product(string.ascii_uppercase, range(10)):
    print(f"{number}{letter}")

相关问题 更多 >