如何在每个索引处删除列表中的文本

2024-06-17 15:28:51 发布

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

我的清单类似于:

['42344 xxxxxx xxxx 12','31232 zzzzzz xxxxx 15','3111 yyyyyy aaaaaa 34']

我需要修改列表,只删除第一个数字,并显示列表,以便在每个逗号后有一个新行。预期产出将是:

xxxxxx xxxx 12
zzzzzz xxxxx 15
yyyyyy aaaaaa 34

我尝试了很多代码,但我现在迷路了,不知道如何达到我想要的输出


Tags: 代码列表数字逗号xxxxxxxxxxxxxxx迷路
3条回答
my_list = ['42344 xxxxxx xxxx 12','31232 zzzzzz xxxxx 15','3111 yyyyyy aaaaaa 34']

#the symbols that should be removed before you reach the one you need
what_should_be_removed = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ']  

i = 0
for string in my_list: #checking each element in my_list
    for char in string:  #checking each character in the phrase
        if char in what_should_be_removed:
            i += 1  
        else:
            print(string[i:]) #slicing the string
            i = 0
            break

您可以通过列表理解在一行中实现这一点:

>>> new_list = [' '.join(i.split()[1:]) for i in old_list]

一种方法是将str.split放在空白处,然后切掉第一个元素,然后join重新组合在一起

data = ['42344 xxxxxx xxxx 12','31232 zzzzzz xxxxx 15','3111 yyyyyy aaaaaa 34']
for line in data:
    print(' '.join(line.split()[1:]))

输出

xxxxxx xxxx 12
zzzzzz xxxxx 15
yyyyyy aaaaaa 34

相关问题 更多 >