簡體   English   中英

將 txt 文件中的字符串拆分為元組列表

[英]split string from txt file into a list of tuples

我有一個看起來像這樣的 txt 文件:

yes,54,good,less
no,55,good,less
no,26,good,less

我想閱讀它並將其表示為成對列表。 對中的第一個元素是包含前三個值的三元組(元組),對中的第二個元素是第四個元素。 使用他的代碼,我可以將每一行轉換為一個元組而不是一對。

import os
path=os.getcwd()
def gettest() -> list:
    with open(path+"\\health-train.txt")as f:
        lines = f.read()
        f = list(lines.split())
        a=[tuple(map(str,sub.split(','))) for sub in f]
    return a

我有這個:

[('yes', '54', 'good', 'less'),
 ('no', '55', 'good', 'less'),
 ('no', '26', 'good', 'less')]

但我想要這個:

[(('yes', '54', 'good'), ('less',)),
 (('no', '55', 'good'), ('less',)),
 (('no', '26', 'good'), ('less',))]

說您以前的元組由變量previous_result存儲。 在這里你 go 代碼:D


result = [(item[:3], (item[-1],)) for item in previous_result]

result
[(('yes', '54', 'good'), ('less',)), 
(('no', '55', 'good'), ('less',)), 
(('no', '26', 'good'), ('less',))]

你有幾種方法。

為此,將f = list(lines.split())a=[tuple(map(str,sub.split(','))) for sub in f]行替換為:

python ≥ 3.8:

a = [(tuple(t := sub.split(','))[:3], (t[3],)) for sub in lines.split()]

python 3

a = [(tuple(a), (b,)) for *a,b in map(lambda x: x.split(','), lines.split())]

所有蟒蛇

a = [(tuple(sub[:3]), (sub[3],)) for sub in map(lambda x: x.split(','), lines.split())]

output 某:

[(('yes', '54', 'good'), ('less')),
 (('no', '55', 'good'), ('less')),
 (('no', '26', 'good'), ('less'))]

您還可以使用元組拆包和重新排列,即

s = """
yes,54,good,less
no,55,good,less
no,26,good,less
"""

lines = [x.split(',') for x in s.split()]  # split into lists of single words
print([((a,b,c),(d,)) for (a,b,c,d) in lines])

Output:

[(('yes', '54', 'good'), ('less',)),
 (('no', '55', 'good'), ('less',)),
 (('no', '26', 'good'), ('less',))]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM