如果列表中没有键和值对,则使用python跳过此数据

2024-09-22 18:33:33 发布

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

我有一个包含键和值数据的数据列表,但有时它只包含数据。我想跳过这类数据。你知道吗

我得到了下面的答案错误:-你知道吗

示例:-

formatted_desc_split = ['Akshay Godase is from pune', 'Amar:Satara', 'Sandesh:Solapur', 'Mahesh:Nagpur', 'Prashant:Indapur']

for each_split_data in formatted_desc_split:
    split_by_colon = each_split_data.split(":")
Error :-
IndexError: list index out of range

我想跳过Akshay Godase is from pune数据。若列表中并没有键和值对,那个么我想跳过这个数据。我无法拆分此数据,因为在第一个索引中没有键值paire。你知道吗

如何解决上述问题?你知道吗


Tags: 数据答案from示例列表datais错误
3条回答

使用列表理解。简洁、易读、易懂:

>>> strings = ['Akshay Godase is from pune', 'Amar:Satara', 'Sandesh:Solapur', 'Mahesh:Nagpur', 'Prashant:Indapur']
>>> [s for s in strings if ':' in s]
['Amar:Satara', 'Sandesh:Solapur', 'Mahesh:Nagpur', 'Prashant:Indapur']

请改为使用以下命令:

formatted_desc_split = ['Akshay Godase is from pune', 'Amar:Satara', 'Sandesh:Solapur', 'Mahesh:Nagpur', 'Prashant:Indapur']

for each_split_data in formatted_desc_split:
    if ":" not in each_split_data:
        ...

可能不是一种优雅的方式,但是下面的代码实现了您想要的。只是为了另一个解决方案。你知道吗

formatted_desc_split = ['Akshay Godase is from pune', 'Amar:Satara', 'Sandesh:Solapur', 'Mahesh:Nagpur', 'Prashant:Indapur']

my_dict = {}

for each_split_data in formatted_desc_split:
    split_by_colon = each_split_data.split(":")
    if len(split_by_colon) == 2:
        my_dict[split_by_colon[0]] = split_by_colon[1]
    print(my_dict)

相关问题 更多 >