python - 如何查找特定数据在数组中的哪条记录?
问题描述
我正在为我的班级编写一个程序,我必须从用户那里获取输入数据并将该数据放入一个记录中,该记录又进入一个数组。
def createArray0fRecords(length):
city_records = ["", "", 0.0,""]#Create record
#City, Country, Population in Millions, Main Language
city_array = [city_records]*length #Create Array of Records
return city_array
def populateRecords(city_array):
for counter in range (0, len(city_array)):
print("")
print("Please enter the city")
city=input()
print('Please enter the country')
country=input()
print("Please enter the population in millions")
population=float(input())
while population < 0:
print(population," isn't a valid answer. Please input a number greater than 0.")
population=input()
print("Please enter the main language")
language = input()
city_array[counter] = [city, country, population, language]
return city_array
def main_program():
print("How many cities will you be entering?")
length = int(input())
city_array = createArray0fRecords(length)
city_array = populateRecords(city_array)
print("What city would you like the information about?")
city=input()
if city in (city_array[1]):
print(city_array[city])
main_program()
我相信我快到了,现在必须更改的只是最后几行。谢谢
对不起,我是堆栈溢出的新手,我意识到我的问题措辞错误,我必须做的是把所有的信息都带进去,然后我必须输入我想获取信息的城市,程序会给我那个城市的信息
解决方案
您可以像这样按相关城市名称过滤 city_array (您可以在此处阅读列表理解)
relevant_cities = [c for c in city_array if c[0] == city]
现在,related_cities 将是具有城市等于用户输入的所有记录的列表。您现在可以检查此列表是否为空,并根据需要执行任何操作。
推荐阅读
- c - 在 VSCode 中使用 gcov
- keras - 可变长度视频分类的数据准备
- python - 如何仅从 Bigquery Client 中的 insert_rows_from_dataframe 方法中获取错误?
- ansys - Ansys Fluent 网格划分和分析
- java - 错误:在类 ca.ab.bc.framework.FormData 中找不到主要方法
- python - 使用异常子句每隔 x 时间运行一段代码
- mysql - MySQL JSON 函数创建分组数据的问题
- javascript - 为什么我会收到此错误:未捕获的 TypeError:this.createLink is not a function at new Link at
1:9? - ruby - 如何使 Ruby Mocha 模拟只检查一个参数
- php - 如果单击链接,如何将默认的 html / php 登录页面更改为另一个页面