[英]How to check if an element exists in multiple lists in python
companies = ['apple','google','tesla','facebook','cisco']
list_1 = ['apple','google','tesla','facebook']
list_2 = ['google','tesla','facebook']
list_3 = ['apple','tesla','cisco']
list_4 = ['apple','google','tesla']
list_5 = ['google','tesla','facebook']
我有熊猫 df 如下 - COMPANY_DF
+--------+---------------------------------------+---------------+
|column1 | column2 | column3 |
+------------------------------------------------+---------------|
|apple | [list_2,list_3,list_4] | |
|google | [list_1,list_2,list_3,list_5] | |
|tesla | [list_1,list_2,list_3,list_4,list_5] | |
|facebook| [list_1,list_2,list_5] | |
|cisco | [list_3] | |
+------------------------------------------------+---------------+
问题 - 对于column3
我必须从column2
的列表中找到其他元素例如 - 对于column1
row 1 apple 我必须在[list_2,list_3,list_4]
( column2
row 1) 中找到其他公司的苹果
我的方法——
for i in range(0, len(COMPANY_DF['column2'])):
column3_list = []
for company in companies:
for j in range(0, len(COMPANY_DF['column2'].loc[i])):
if company in COMPANY_DF['column2'].loc[i][j]:
company.append(column3_list)
else:
print('Not there')
COMPANY_DF['column3'].loc[i] = column3_list
我对这个 if 语句有疑问 -
if company in COMPANY_DF['column2'].loc[i][j]:
if company in COMPANY_DF['column2'].loc[i][j] is
giving 'list_2' instead of list_2 I believe that's why it's failing.
任何帮助表示赞赏。
这是我的方法:
companies = ['apple','google','tesla','facebook','cisco']
list_1 = ['apple','google','tesla','facebook']
list_2 = ['google','tesla','facebook']
list_3 = ['apple','tesla','cisco']
list_4 = ['apple','google','tesla']
list_5 = ['google','tesla','facebook']
list_of_lists = [f'list_{i}' for i in range(1, 6)]
# will create a string named the same for each of the lists,
# so it can be added to the list of mentions later, and also evaluated.
company_mentions = []
for company in companies:
mentions = [mention for mention in list_of_lists if company in eval(mention)]
# a list of the lists that a particular company has been mentioned in.
company_mentions.append(mentions)
# will append a list of the lists that company is mentioned in.
希望这可以帮助。
编辑:如果您希望拥有整个列表,则可以在附加时在mentions
周围添加eval
。 什么对你最有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.