如何使用python拆分行并获取剩余的行

问题描述 投票:0回答:3

我的文件中有一些行

0 1 2 3 4 5
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6

我正在尝试拆分但是我收到错误我想要排除0 1并想要选择剩下的行但是我怎么能用python做到这一点

elm1 = line.split()[0]
elm2 = line.split()[1]
elm3 = line.split()[2] +" "+ [3] +" "+ [4] +" "+ [5] +" "+ [6] +" "+ [7]
python
3个回答
2
投票

你是说这个吗?

>>> line = "0 1 2 3 4 5 6 7"
>>> " ".join(line.split()[2:])
'2 3 4 5 6 7'

0
投票

我不明白你的意思是“选择剩下的线”,但要拆分线并排除01你可以使用join()split()

line1 = '0 1 2 3 4 5'
line2 = '0 1 2 3 4 5 6 7'
line3 = '0 1 2 3 4 5 6'

filtered1 = ' '.join(num for num in line1.split() if num != '0' and num != '1')
filtered2 = ' '.join(num for num in line2.split() if num != '0' and num != '1')
filtered3 = ' '.join(num for num in line3.split() if num != '0' and num != '1')

print(filtered1)
print(filtered2)
print(filtered3)

产量

2 3 4 5

2 3 4 5 6 7

2 3 4 5 6


0
投票

您可以使用参数maxsplit

>>> s = "1 2 3 4 5 6 7 8"
>>> s.split(maxsplit=2)
['1', '2', '3 4 5 6 7 8']
>>> elm1,elm2,elm3 = tuple(s.split(maxsplit=2))
© www.soinside.com 2019 - 2024. All rights reserved.