Я предоставлю вам несколько методов подбора людей по городу в Python, а также примеры кода. Вот несколько подходов, которые вы можете рассмотреть:
Метод 1: использование словаря
people = [
{"name": "John", "city": "New York"},
{"name": "Alice", "city": "London"},
{"name": "Bob", "city": "Paris"},
# Add more people here
]
def find_people_by_city(people_list, city):
matching_people = []
for person in people_list:
if person["city"] == city:
matching_people.append(person)
return matching_people
city = "London"
matching_people = find_people_by_city(people, city)
print("People in", city + ":")
for person in matching_people:
print(person["name"])
Метод 2: использование понимания списка
matching_people = [person for person in people if person["city"] == city]
print("People in", city + ":")
for person in matching_people:
print(person["name"])
Метод 3. Использование библиотеки pandas
import pandas as pd
people_df = pd.DataFrame(people)
matching_people = people_df.loc[people_df["city"] == city]
print("People in", city + ":")
for index, row in matching_people.iterrows():
print(row["name"])
Метод 4. Использование функции filter()
matching_people = list(filter(lambda person: person["city"] == city, people))
print("People in", city + ":")
for person in matching_people:
print(person["name"])
Метод 5. Использование подхода на основе классов
class Person:
def __init__(self, name, city):
self.name = name
self.city = city
people = [
Person("John", "New York"),
Person("Alice", "London"),
Person("Bob", "Paris"),
# Add more people here
]
matching_people = [person.name for person in people if person.city == city]
print("People in", city + ":")
for person_name in matching_people:
print(person_name)