简体   繁体   English

在 Python 中的列表列表中搜索/查找

[英]Search/Find within a List of Lists in Python

I have a list of lists and I'm trying to search or address data within the lists.我有一个列表列表,我正在尝试在列表中搜索或寻址数据。

Eg例如

print(data[0])
print(data[12])

Gives me给我

['Spinward-Rimward', 'Sol', 0, 0, 'N/A', '']
['Spinward-Rimward', 'POL-6387', 2, -8, 'TWE', 'Atol']

And

print(data[0][0])

gives me给我

Spinward-Rimward

And I can get an individual item我可以得到一个单独的项目

index = data[0].index('Sol')
print(index)

Gets me得到我

1

But searching within the lists of lists is boggling me.但是在列表列表中搜索让我感到难以置信。 I have a few hundred lines of data and if I wanted every row that contained Spinward-Rimward or every row where Latitude and Longtitude were less than 10, I'm pretty stumped.我有几百行数据,如果我想要包含 Spinward-Rimward 的每一行或纬度和经度小于 10 的每一行,我很难过。

I need this because I plan to be running arithmetic operations on the Lat/Long when people enter the name of the Star System to find the distance between two stars.我需要这个,因为我计划在人们输入恒星系统的名称以查找两颗恒星之间的距离时在纬度/经度上运行算术运算。

tl;dr - I'm a python noob who is in lockdown and decided to make a fun toy for players of the Alien RPG which has a 2d map of 3D space. tl;博士 - 我是一个 python 菜鸟,他处于锁定状态,并决定为外星 RPG 的玩家制作一个有趣的玩具,该玩具具有 3D 空间的 2d map。

if I wanted every row that contained Spinward-Rimward or every row where Latitude and Longtitude were less than 10如果我想要包含 Spinward-Rimward 的每一行或纬度和经度小于 10 的每一行

The first is pretty straightforward, you already know the answer:第一个非常简单,您已经知道答案:

for item in data:
    if item[0] == 'Spinward-Rimward':
        print(item)

For the second, you will find tuple unpack to be convenient:对于第二个,你会发现 tuple unpack 很方便:

for spin, star, lat, lng, *_ in data:
    if lat <= 10 and lng <= 10:
        print(item)

That * star syntax means "gimme the rest" as a list, and using _ underscore as a variable name is a conventional way of saying "I won't use this value so I won't even bother giving it a real name."那个*星语法意味着“给我剩下的”作为一个列表,并且使用_下划线作为变量名是一种传统的说法,即“我不会使用这个值,所以我什至不会费心给它一个真实的名字。” For extra credit we could use that syntax to modify the answer to your first question:为了获得额外的荣誉,我们可以使用该语法来修改您的第一个问题的答案:

for spin, *rest in data:
    if spin == 'Spinward-Rimward':
        print(rest)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM