[英]checking if the item exists in the list
I have two sets like A={"sara", "peter", "ray"} and B={"ram", "sara", "gouri"}.我有两组像 A={"sara", "peter", "ray"} 和 B={"ram", "sara", "gouri"}。 I want to take one member of list B (for example "sara") and check with list A to see if this name exists in the list or not.
我想获取列表 B 的一个成员(例如“sara”)并检查列表 A 以查看该名称是否存在于列表中。 If this name exists then print "yes".
如果此名称存在,则打印“是”。 I want to check all the members in list B with list A. I have the code below but it doesn't work.
我想用列表 A 检查列表 B 中的所有成员。我有下面的代码,但它不起作用。
for i in B:
if B[i]==A:
print("yes")
It's easier than you think:这比你想象的要容易:
for i in B:
if i in A:
print("yes")
This assumes that both A and B are lists, but you seem to have dictionaries/sets.这假设 A 和 B 都是列表,但您似乎有字典/集。 You might need to clarify that first.
您可能需要先澄清这一点。 If you have sets, the above solution should still work.
如果您有套装,上述解决方案应该仍然有效。
Edit: you now say that both A and B are columns from two separate DataFrames.编辑:您现在说 A 和 B 都是来自两个单独的 DataFrame 的列。 In that case you can do:
在这种情况下,您可以这样做:
A={"sara", "peter", "ray"}
B={"ram", "sara", "gouri"}
df1 = pd.DataFrame(A, columns=['Names'])
df2 = pd.DataFrame(B, columns=['Names'])
for index, row in df1.iterrows():
if row['Names'] in df2.Names.tolist():
print('yes')
Edit 2: you now say that you want to add the result to a new column in df2.编辑 2:您现在说要将结果添加到 df2 中的新列。 Use:
利用:
A={"sara", "peter", "ray"}
B={"ram", "sara", "gouri"}
df1 = pd.DataFrame(A, columns=['Names'])
df2 = pd.DataFrame(B, columns=['Names'])
df2['present_in_df1'] = np.where(df1['Names'] == df2['Names'], "yes", "no")
Output df2
: Output
df2
:
Names present_in_df1
0 gouri no
1 ram no
2 sara yes
I think you're looking for the in
keyword.我认为您正在寻找
in
关键字。 Breaking this down:打破这个:
(for example "sara") and check with list A to see if this name exists in the list or not.
(例如“sara”)并检查列表 A 以查看该名称是否存在于列表中。 If this name exists then print "yes"
如果此名称存在,则打印“是”
if "sara" in B:
print("yes")
I want to check all the members in list B with list A.
我想用列表 A 检查列表 B 中的所有成员。
for b in B:
if b in A:
print("yes")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.