简体   繁体   English

Python:将列表中字符串项目的索引号附加到该项目

[英]Python: Appending the index number of a string item in a list to that item

For any given list of string items, eg对于任何给定的字符串项目列表,例如

my_list = ['foo', 'bar', 'baz', 'foo']

How does one append the index number of each item to it's corresponding item in the list?如何将每个项目的索引号附加到列表中的相应项目? Forming a new list with the format, eg使用格式形成一个新列表,例如

new_list = ['foo0', 'bar1', 'baz2', 'foo3']

My example list only has four items, but I'm interested in a generalised answer for an arbitrary number of string items (something that works as well for a list of 4,000 string items as it does for 4)我的示例列表只有四个项目,但我对任意数量的字符串项目的通用答案感兴趣(对于 4,000 个字符串项目的列表也适用,就像对 4 个项目一样)

Cheers!干杯!

A simpler way:一个更简单的方法:

new_list = [elm + str(index) for index, elm in enumerate(my_list)]

UPDATE : With Python 3.6+ and formatted strings literals you can get a more readable code:更新:使用 Python 3.6+ 和格式化字符串文字,您可以获得更易读的代码:

new_list = [f'{elm}{index}' for index, elm in enumerate(my_list)]

A straight for loop would work:一个直接的 for 循环可以工作:

counter = 0
new_list = []
for each_item in the_list:
    new_list.append(each_item + str(counter))
    counter += 1

A list comprehension with enumerate() would also be fine, but less readable:使用enumerate()列表理解也可以,但可读性较差:

new_list = [each_item + str(index) for each_item, index in enumerate(the_list)]

try this.尝试这个。

EDIT: Explanation: The function below takes a list as an input and returns a list with the element numbers appended to the item.编辑:说明:下面的函数将列表作为输入并返回一个列表,其中元素编号附加到项目。 The number appended to the end of each item in the list is padded with zeros based on the length of the input list.附加到列表中每个项目末尾的数字根据输入列表的长度用零填充。 So a list of length 30 with have appended numbers 00 through 29;因此,长度为 30 且附加数字 00 到 29 的列表; a list of 3901 will have appended numbers 0000 through 3900. 3901 的列表将附加数字 0000 到 3900。

from numpy import log10

def numberedList(inlist):
    i = 0
    z = int(log10(len(inlist))) + 1
    outlist = []
    for element in inlist:
        outlist.append(str(element) + str(i).zfill(z))
        i = i + 1
    return outlist

To create a list from a static list and a repeating list:从静态列表和重复列表创建列表:

# need: ['A','B','C','First1','Middle1','Last1','First2','Middle2','Last2',...]
['A','B','C']+[s+str(n) for n in range(1,len(names)+1) for s in ['First','Middle','Last']]

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

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