gpt4 book ai didi

python - 在 Python 中从数组中删除一个字符串

转载 作者:太空宇宙 更新时间:2023-11-04 08:40:08 25 4
gpt4 key购买 nike

我正在用 Python 编写一些代码以从文件中读取一些文本,并从中创建一个二维数组。但是当我制作数组时,在前 2 个数组(共三个)的最后一个位置有:'\n',我想删除它。

这是文件(data.txt):

a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z

这是 Python 代码:

data = open("data.txt", mode="r")

arr = data.readlines()

for i in range(len(arr)):
arr[i] = list(arr[i].split(","))

#here I tryed to detele it
for i in range(len(arr)):
if arr[i][len(arr[i])-1] == '\\n':
del arr[len(arr[i])-1]

data.close()

这是代码的结果(但无论如何都有'\n'):

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\n']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\n']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

我怎样才能删除那些?

最佳答案

使用 str.rstrip()str.splitlines() 函数的简短解决方案:

with open('data.txt', 'r') as f:
items = [l.rstrip(',').split(',') for l in f.read().splitlines()]
print(items)

输出:

[['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']]

关于python - 在 Python 中从数组中删除一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45533783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com