拆分一个字符串,该字符串位于两个元素中的列表列表中,这两个元素保留在同一列表中

时间:2018-05-19 17:12:04

标签: python python-3.x list int tuples

这是我导入并希望转换为特定列表的文本文件中的数字链。

3 04,24
4 04,75
4 05,11
4 05,47
4 05,78
4 06,80
3 07,25
3 07,92
3 08,23
2 09,76

实际上,在我的代码中,我达到了这一点:

[['3 04,24'], ['4 04,75'], ['4 05,11'], ['4 05,47'], ['4 05,78'], ['4 06,80'], ['3 07,25'], ['3 07,92'], ['3 08,23'], ['2 09,76']]

但是我想把元组中的元素分成两部分来得到这样的东西:

[['3','04,24'], ['4','04,75']] etc...

但经过多次研究后我找不到解决方案,如果你能告诉我如何将这些元素从字符串转换为int,这将非常有用!

这是我的代码:

with open("myfile.txt") as f:
    mylist = [line.rstrip('\n') for line in f]
    mylist = [mylist[x:x+1] for x in range(0, len(mylist), 1)]
    print(mylist)

感谢。

4 个答案:

答案 0 :(得分:1)

这是使用标准库中的csv模块的一个解决方案:

import csv

with open('myfile.txt', 'r') as f:
    reader = csv.reader(f, delimiter=' ')
    res = list(reader)

您的数据示例: -

from io import StringIO
import csv

mystr = StringIO("""3 04,24
4 04,75
4 05,11
4 05,47
4 05,78
4 06,80
3 07,25
3 07,92
3 08,23
2 09,76""")

with mystr as f:
    reader = csv.reader(f, delimiter=' ')
    res = list(reader)

print(res)

# [['3', '04,24'],
#  ['4', '04,75'],
#  ['4', '05,11'],
#  ['4', '05,47'],
#  ['4', '05,78'],
#  ['4', '06,80'],
#  ['3', '07,25'],
#  ['3', '07,92'],
#  ['3', '08,23'],
#  ['2', '09,76']]

或者如果您需要将数据转换为数字:

with mystr as f:
    reader = csv.reader(f, delimiter=' ')
    res = [[int(i), float(j.replace(',', '.'))] for i, j in reader]

print(res)

[[3, 4.24],
 [4, 4.75],
 [4, 5.11],
 ...

答案 1 :(得分:1)

使用list-comprehension:

>>> lst = [['3 04.24'], ['4 04.75'], ['4 05.11'], ['4 05.47'], ['4 05.78'], ['4 06.80'], ['3 07.25'], ['3 07.92'], ['3 08.23'], ['2 09.76']]
>>> [x[0].split() for x in lst]

输出:

[['3', '04.24'], 
 ['4', '04.75'], 
 ['4', '05.11'], 
 ['4', '05.47'], 
 ['4', '05.78'], 
 ['4', '06.80'], 
 ['3', '07.25'], 
 ['3', '07.92'], 
 ['3', '08.23'], 
 ['2', '09.76']]            

将字符串转换为整数:

[[int(i) if not '.' in i else float(i) for i in x[0].split()] for x in lst]

答案 2 :(得分:1)

使用str.split()方法:

with open("myfile.txt") as f:
    mylist = [line.rstrip('\n') for line in f]
    my_structured_list = [line.split(" ") for line in mylist]

    print(my_structured_list)

关于将元素转换为int的问题的第二部分,您可以再次使用str.split()并将结果元素转换为int

with open("myfile.txt") as f:
    mylist = [line.rstrip('\n') for line in f]
    my_structured_list = [line.split(" ") for line in mylist]

    my_structured_int_list = []
    for line_tuple in my_structured_list:
        input_first_element = line_tuple[0]
        input_second_element, input_third_element = line_tuple[1].split(",")

        output_first_half = int(input_first_element)
        output_second_half = int(input_second_element), int(input_third_element)

        my_structured_int_list.append((output_first_half, output_second_half))

    print(my_structured_int_list)

答案 3 :(得分:0)

简单的解决方案如下

with open(file,'r') as f:
    print([each.split() for each in f])