data_set = ["This is cool jacket","I have two white shirts","I need black leather jacket", "I have five half shirts"]
shirt_list = []
jacket_list = []
def parse_data(clothes):
for i in clothes:
if "Jacket" in data_set:
jacket_list.append(i)
elif "shirt" in data_set:
shirt_list.append(i)
else:
pass
return shirt_list,jacket_list
print(parse_data(data_set))
我需要对特定字符串中的数据进行排序和收集,以便在我需要的代码中将夹克字符串打印在Jacket_list中,类似于衬衫。我尝试使用此代码不起作用。
答案 0 :(得分:1)
快速解决您的问题是:
data_set = ["This is cool jacket","I have two white shirts","I need black leather jacket", "I have five half shirts"]
shirt_list = []
jacket_list = []
def parse_data(clothes):
for i in clothes:
if "jacket" in i:
jacket_list.append(i)
elif "shirt" in i:
shirt_list.append(i)
else:
pass
return shirt_list,jacket_list
print(parse_data(data_set))
原因是你试图查看总列表,而是查看每个i
然后我会将支票更改为更多通用支票,如下所示:
if "JACKET" in i.upper():
jacket_list.append(i)
elif "SHIRT" in i.upper():
shirt_list.append(i)
这将有助于消除列表中更改的可能性
修改强>
如果您还想检查黑色,可以这样做:
for i in clothes:
if "jacket" in i:
if "black" in i:
jacket_list.append(i)
elif "shirt" in i:
if "black" in i:
shirt_list.append(i)
else:
pass
所有它正在做的是在里面添加一个额外的if语句,可能是更多的代码,但我认为它更容易阅读。
如果你想在同一个if语句中使用它,只需添加:
if "jacket" in i and "black" in i: