简体   繁体   English

将数字添加到字符串列表中

[英]Adding numbers to a list of strings

Im trying to modify a list of strings so the elements will have element numbers at front starting from 1 . 我试图修改字符串列表,以便元素从1开始在前面有元素编号。

For example: 例如:

['John', 'Eric', 'Samuel'] becomes ['1 John', '2 Eric', '3 Samuel'] ['John', 'Eric', 'Samuel']成为['1 John', '2 Eric', '3 Samuel']

Here is the code i have so far: 这是我到目前为止的代码:

for i in range(len(rader)):
    rader[i] = '{}{}{}'.format(i," ",rader[i])

This adds a number before but the problem is that it gives the first string number zero, how do I work around this? 这之前添加了一个数字,但问题是它给第一个字符串数字为零,我该如何解决这个问题呢?

You can pass i + 1 to format() : 你可以将i + 1传递给format()

for i in range(len(rader)):
    rader[i] = '{}{}{}'.format(i + 1," ",rader[i])
    #                          ^^^^^

But there exists a more elegant way: 但是存在一种更优雅的方式:

for i, name in enumerate(rader):
    rader[i] = '{} {}'.format(i + 1, name)

You can use enumerate , just specify start and it'll start from 1 : 您可以使用enumerate ,只需指定start ,它将从1开始:

rader = ['{} {}'.format(i,s) for i,s  in enumerate(rader, start=1)]

And if you just want to print it that way: 如果你只想以这种方式print它:

print(*('{} {}'.format(i,s) for i,s in enumerate(rader, start=1)), sep=', ')

Output: 输出:

1 John, 2 Eric, 3 Samuel

You can pass additional arguments for range function, for example: 您可以为范围函数传递其他参数,例如:

 for i in range(1,len(rader))

More about range function 更多关于范围功能

But for this solution you'd need to re-numerate rest of you code though, so it's probably not best idea. 但是对于这个解决方案,你需要重新计算其余的代码,所以这可能不是最好的主意。

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

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