若列表中并没有键和值对,那个么使用python跳过此数据
我有一个包含键和值数据的数据列表,但有时它只包含数据。我想跳过这类数据 我得到以下错误:- 例如:-若列表中并没有键和值对,那个么使用python跳过此数据,python,list,split,Python,List,Split,我有一个包含键和值数据的数据列表,但有时它只包含数据。我想跳过这类数据 我得到以下错误:- 例如:- 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_sp
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(":")
我想跳过Akshay Godase来自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']
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)
这可能不是一种优雅的方式,但是下面的代码可以满足您的需要。只是为了另一种解决方案
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)
使用列表理解。简明易读,通俗易懂:
>>> 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']
使用列表理解。简明易读,通俗易懂:
>>> 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']