如何使用For循环将整数作为字符串添加到列表中?

2024-10-06 12:35:18 发布

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

我创建了以下列表:

Stores = ['Costco','Publix', 'Kroger', 'Target']

我被要求创建另一个列表(Store\u Rank),通过在前面添加整数来定义它们的排名。但是,整数应该是列表格式。你知道吗

我假设使用f插值?你知道吗

“商店排名”列表应输出以下内容:

1. Costco, 2. Publix, 3. Kroger, 4. Target

注:预期结果为

  Store_Rank [0] = 1. Costco

  Store_Rank[2] =  2. Publix

等等。。你知道吗

请帮帮我!你知道吗


Tags: storetarget列表定义格式整数stores商店
3条回答

使用enumerate的短代码

Store_Rank = [str(idx) + ". " + store for idx, store in enumerate(Stores, start=1)]

使用代码:

Stores = [Costco, Publix, Kroger, Target]
Store_rank = []
for i in range(0, len(Stores)):
    Store_rank.append(str(i+1) + ". " + Stores[i])

如果您使用的是Python3.6+,则可以使用列表和f字符串,如下所示:

>>> Stores = ['Costco','Publix', 'Kroger', 'Target']
>>> [f'{i}. {store}' for i, store in enumerate(Stores, start=1)]
['1. Costco', '2. Publix', '3. Kroger', '4. Target']

相关问题 更多 >