简体   繁体   中英

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.

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.

if I wanted every row that contained Spinward-Rimward or every row where Latitude and Longtitude were less than 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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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