我们如何分割数据输入,其中一些由一个空间分隔,另一些由两个空间分隔?

2024-04-24 05:52:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据输入如下:

[-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914]
[ 228 -114 -114  914  228 -114 -114  228  228 -114 -114  228  228 -114 -114]

正如你所看到的,负数前有一个空格,正数前有两个空格

我将文件读为:

def switch(letter):
    switcher = {
        "[": "",
        "]": "",
        "\n": "@",
    }
    return switcher.get(letter, letter)


converted_data = ''
with open("/Users/naghmeh/Documents/python/core1", "r") as file:
    data = file.read()

for letter in data:
    letter = switch(letter)
    converted_data = converted_data+letter

converted_data = converted_data.split('@')
split_converted_data = []
for i in converted_data:
    i = i.split(" ")
    split_converted_data.append(i)  

其中i = i.split(" ")以1个空格分隔。因此,代码无法正确运行。我怎么能修好它


3条回答

^{} documentation中,您可以找到:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

因此,使用split()而不指示分隔符

"-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914".split()

使用不带参数的split()

a = '-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914'
a = a.split()
print(a)
# ['-114', '-114', '228', '-114', '228', '228', '-114', '-114', '228', '228', '-114', '228', '-114', '-114', '914']

你可以做:

for i in converted_data:    
    i = i.replace('  ', ' ').split(' ')
    split_converted_data.append(i) 

将每对空间仅替换为一个

相关问题 更多 >