我正在尝试创建一个程序,该程序将通过给它们一个从 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
谢谢!
这样做的标准方法是itertools.product
,它作为某种"多for 循环"。
import itertools
import string
for letter, number in itertools.product(string.ascii_uppercase, range(10)):
print(f"{number}{letter}")
尝试:
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='')
像这样更改 for 循环:
for id, product in zip(fruit_id, products_fruit):
print("0" + str(id%10) + str(alphabet[id//10]) + " =", product)