如何从列表元素中删除 ? [英] How to remove from a list element?
问题描述
我试图让 Python 从 .txt 文件读取一行并将第一行的元素写入列表.文件中的元素是制表符分隔的,所以我使用 split(" ")
来分隔元素.因为 .txt 文件有很多元素,所以我将每行找到的数据保存到一个单独的列表中.
I'm trying to get Python to a read line from a .txt file and write the elements of the first line into a list. The elements in the file were tab- separated so I used split(" ")
to separate the elements. Because the .txt file has a lot of elements I saved the data found in each line into a separate list.
我目前遇到的问题是它显示每个列表是这样的:
The problem I currently have is that it's showing each list like this:
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3
']
如何从列表的最后一个元素中删除
并使其成为 '7.3'
?
How can I remove
from the last element of the list and make it just '7.3'
?
推荐答案
如果您只想从最后一个元素中删除
,请使用:
If you want to remove
from the last element only, use this:
t[-1] = t[-1].strip()
如果要从所有元素中删除
,请使用:
If you want to remove
from all the elements, use this:
t = map(lambda s: s.strip(), t)
您也可以考虑在拆分行之前删除
:
You might also consider removing
before splitting the line:
line = line.strip()
# split line...
这篇关于如何从列表元素中删除 ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!