Reputation: 11
I have a list of lists and I'm trying to search or address data within the lists.
E.g.
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.
Upvotes: 0
Views: 56
Reputation: 89
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)
Upvotes: 1