繁体   English   中英

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

[英]if there is not key and value pair in list then skip this data using 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数据。 如果列表中没有键和值对,那么我想跳过此数据。 我无法拆分此数据,因为在第一个索引中没有键值对。

我该如何解决以上问题?

请改用以下内容:

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)

使用列表理解。 简洁,可读,pythonic:

>>> 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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM