Python从文本文件中删除

2024-04-26 14:02:40 发布

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

所以基本上在我的文本文件中,信息是这样排列的

([x,x,x,x,x,x,x,x,x,x,,x],[x,x,x,x],[x,x,x])

我如何去掉方括号,使它成为一个数组,并且我可以通过position[0]position[10]调用它?你知道吗


Tags: 信息position数组文本文件方括号
2条回答

你可以像这样循环在元组中的列表上,将它们展平。你知道吗

tuple_of_lists = ([x,x,x,x,x,x,x,x,x,x,,x],[x,x,x,x],[x,x,x])
resulting_list = []
for lis in tuple_of_lists:
    resulting_list.extend(lis)

希望对你有帮助。你知道吗

你知道吗编辑时间:- 也许这个功能能帮上忙。你知道吗

def formatter(string):
    l = len(string)
    to_avoid = {',', '[', ']', '(', ')', '"'}
    lis = []
    temp = ''
    for i in range(l):
        if string[i] in to_avoid:
            if temp != '':
                lis.append(temp)
            temp = ''
            continue
        else:
            temp += string[i]
    return lis

有帮助吗?试用:

list2=r"([x,x,x,x,x,x,x,x,x,x,,x],[x,x,x,x],[x,x,x])"

old_list=[i for i in list2]

new_list=[i for i in old_list if i!=',' and i!='(' and i!=')' and i!='[' and i!=']']

print(new_list)

输出:

['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x']

Update soltion basis on your screenshot :

list_22=([1,2,3,4],["couple A","couple B","couple C"],["f","g","h"])

print([j for i in list_22 for j in i])

输出:

[1, 2, 3, 4, 'couple A', 'couple B', 'couple C', 'f', 'g', 'h']

相关问题 更多 >