[英]How to check first name and last name is in a list of names in Python? Is it possible?
The scenario is like this, I'm checking 2 strings in a list, I have a variable containing a string of first name, and a variable containing a last name.场景是这样的,我正在检查列表中的 2 个字符串,我有一个包含名字字符串的变量和一个包含姓氏的变量。 And a list containing only strings of their full names.以及一个仅包含其全名字符串的列表。 I tried using "and" so that if the first name and the last name are both true we can say that the full name in the list is indeed true, I want them to compare to the list of it's original full name so that it will give me a Boolean value of True.我尝试使用“和”,这样如果名字和姓氏都为真,我们就可以说列表中的全名确实为真,我希望它们与原始全名的列表进行比较,以便它会给我 Boolean 的 True 值。 But I'm having problem because if I change either one, it still gives off a result of True.但我遇到了问题,因为如果我更改其中任何一个,它仍然会给出 True 的结果。 Is my scenario possible?我的场景可能吗? or if not is there any work-around?或者如果没有,是否有任何解决方法? Here is the idea of the code this doesn't work I just used this to explain my work, I hope this may help to visualize my question.这是代码的想法这不起作用我只是用它来解释我的工作,我希望这可以帮助形象化我的问题。
first_name = 'John Eric'
last_name = 'Delos Santos'
list = ['Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric']
if last_name and first_name in list:
print(True)
else:
print(False)
I would appreciate your kind response, Thank you!非常感谢您的友好回复,谢谢!
From your example, it looks like a pattern possibility is there in the list
ie <lastname>, <firstname>
.从您的示例来看, list
中似乎存在模式可能性,即<lastname>, <firstname>
。 So you can just search this string in the list
所以你可以在list
中搜索这个字符串
Your condition can become你的情况可能会变成
if f"{last_name}, {first_name}" in list:
print(True)
else:
print(False)
If such a pattern isn't consistent, then you can use this to find the result如果这样的模式不一致,那么您可以使用它来查找结果
result = next((True for i in list if first_name in i and last_name in i), False)
print(result)
This will iterate all the names and check for occurrences of first_name
and last_name
in each individual string.这将迭代所有名称并检查每个字符串中是否出现first_name
和last_name
。 If it succeeds, it will return True
, or else it will fallback to False
which you can print如果成功,它将返回True
,否则它将回退到您可以打印的False
I assume that the list is always ordered in the same way, so you can do:我假设列表总是以相同的方式排序,所以你可以这样做:
first_name = 'John Eric'
last_name = 'Delos Santos'
YourList = ['Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric', 'Delos Santos, John Eric']
full_name = last_name + ", " + first_name
if full_name in YourList:
print(True)
else:
print(False)
If not, please let me know!如果没有,请告诉我!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.