我的文件中有一些行
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]
你是说这个吗?
>>> line = "0 1 2 3 4 5 6 7"
>>> " ".join(line.split()[2:])
'2 3 4 5 6 7'
我不明白你的意思是“选择剩下的线”,但要拆分线并排除0
和1
你可以使用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
您可以使用参数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))