Python搜索嵌套列表

时间:2016-06-27 13:11:38

标签: python

我有一个名为player的嵌套列表,如下所示:

players = [["PlayerA", "10", "20"], ["PlayerB", "15", "30"], ["PlayerC", "15", "30"] ]

我希望能够使用输入语句按播放器名称(PlayerA,PlayerB等)进行搜索,如果搜索与项目匹配,则打印出整个项目。我将如何做到这一点,我正在尝试学习不同的方法。

search = input("Please enter the players name")
for item in players:
  if item == search:
     print(item)
  else:
     print("item not found")

当我执行上述操作时,它会继续打印未找到的项目。

非常感谢提前。

4 个答案:

答案 0 :(得分:4)

if item == search:

此条件不会成功,因为item["PlayerA", "10", "20"]search"PlayerA"。列表永远不会与字符串相等。

尝试将searchitem的第一个元素进行比较。

if item[0] == search:

答案 1 :(得分:4)

它未打印"项目的原因"是因为您要将子列表与要查找的字符串进行比较,例如

["PlayerA", "10", "20"] == "PlayerA"

当然是假的。您需要从每个子列表中提取名称。

您可以这样做的一种方法是使用filter,如下所示:

filter(lambda record: record[0] == "PlayerA", players)

这将返回一个记录列表,其中第0个元素匹配" PlayerA"。

答案 2 :(得分:2)

您需要访问第一个元素或嵌套列表。 像这样:

for player in players:
    if player[0] == input:
        return player

答案 3 :(得分:1)

是的,只是让你像这样编码:

players = [["PlayerA", "10", "20"], ["PlayerB", "15", "30"], ["PlayerC", "15", "30"] ]
search = input("Please enter the players name: ")

result = [player for player in players if player[0] == search]

if result == []:
    print("item not found")
else:
    print(result)