首页 > 解决方案 > 在字符串的开头添加一个数字

问题描述

我正在尝试从一行中读取字符串并在每个字符串的开头添加一个数字并将每个添加到一个数组中,但是我的代码将一个数字添加到字符串的每个字符。

infile = open("milkin.txt","r").readlines()
outfile = open("milkout.txt","w")

number = infile[0]
arrayLoc = infile[1].split( )
array = infile[2].split( )

for i in infile[2]:
    counter = 1
    countered = str(counter)
    i = countered + i
    array.append(i)

output:
['2234567', '3222222', '4333333', '5444444', '6555555', '11', '12', '13', '14', '15', '16', '17', '1 ', '12' .... etc

intended output:
['12234567', '23222222', '34333333', '45444444', '56555555']

infile:
5
1 3 4 5 2
2234567 3222222 4333333 5444444 6555555

标签: pythonarraysloopssplitio

解决方案


您需要遍历array从文件中读取的内容,并且由于看起来您想为每个元素添加序号,因此您可以enumerate(array)在循环时使用它来获取每个元素的索引。您可以添加一个参数来enumerate告诉它从哪个数字开始(默认为 0):

new_arr = []
for i, a in enumerate(array, 1):
    # 'i' will go from 1, 2, ... (n + 1) where 'n' is number of elements in 'array'
    # 'a' will be the ith element of 'array'
    new_arr.append(str(i) + a)
print(new_arr)

['12234567', '23222222', '34333333', '45444444', '56555555']

正如评论中所指出的,这可以使用列表推导更简洁地完成,这是更 Pythonic 的循环方式:

new_arr = [str(i) + a for i, a in enumerate(array, 1)]

推荐阅读