我希望我的程序返回txt文件中除0
以外的所有数字。
我的txt文件中的变量如下[10 20 30 40 0 5 3 21 0]
import os
num= ''
f1 = open("3data.txt", 'r')
for line in f1:
num = line.split("0")
print(num)
结果为['1', ' 2', ' 3', ' 4', ' ', ' 5 3 21 ', '']
我想删除0
,但不删除0
之类的数字中的10
吗?
答案 0 :(得分:0)
尝试一下:
fin = []
f = open("3data.txt", "r")
theFullText = f.read()
words = theFullText.split()
for word in words:
fin.append(word)
remove = '0'
fin = [i for i in fin if i != remove]
print(fin)
输入:
10 3 43 20 5 7 0 3 5 7
123
23
3434 434 3 4 34
输出:
['10', '3', '43', '20', '5', '7', '3', '5', '7', '123', '23', '3434',
'434', '3', '4', '34']
答案 1 :(得分:0)
如果您想将该行保留为字符串,则删除只会删除该元素的第一个实例,请尝试以下操作:
import os
num= ''
f1 = open("3data.txt", 'r')
for line in f1:
x = line.split()
print(x)
x = list(filter(lambda a: a != '0', x))
print(x)
答案 2 :(得分:0)
您可以使用以下代码:
with open('3data.txt','r') as fp:
for line in fp:
line = line.translate(None,'][') #no translation matrix, just deletion
elems = line.split() #separator is space
elems = [x if x !='0' else '' for x in elems] #replace the '0' by empty string ''
print(elems) #print the newly generated lines
输入:
[10 20 30 40 0 5 3 21 0]
输出:
['10', '20', '30', '40', '', '5', '3', '21', '']
说明:
答案 3 :(得分:-1)
使用您的代码->
import os
num= ''
f1 = open("3data.txt", 'r')
for line in f1:
if line !="0":
print(num)