python - 在字符串的开头添加一个数字
问题描述
我正在尝试从一行中读取字符串并在每个字符串的开头添加一个数字并将每个添加到一个数组中,但是我的代码将一个数字添加到字符串的每个字符。
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
解决方案
您需要遍历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)]
推荐阅读
- sql-server - 联合所有 2 个不同的表
- android - 应用程序崩溃在三星 Galaxy S9+ (star2qltesq)、Android 8.0 上做出本机反应
- node.js - 如何在 Google 图片 URL 图表中显示每个条的大小(值)
- python - 使用机器学习 (SVM) 和 Quandl 预测黄金价格
- java - Intellij 和 Eclipse 无法找到库工件
- c# - 如何使用 XPath 查询选择 XML 节点
- c# - 无法以编程方式从应用程序打开 App Store
- python - Python程序在给定的字符串中放置正确的标点符号
- mysql - 如何选择过去 30 天的数据并包含空行
- html - HTML