Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

python - How to remove from a list element?

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
']

How can I remove from the last element of the list and make it just '7.3'?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...