首页 > 解决方案 > 如何查找特定数据在数组中的哪条记录?

问题描述

我正在为我的班级编写一个程序,我必须从用户那里获取输入数据并将该数据放入一个记录中,该记录又进入一个数组。

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()

我相信我快到了,现在必须更改的只是最后几行。谢谢

对不起,我是堆栈溢出的新手,我意识到我的问题措辞错误,我必须做的是把所有的信息都带进去,然后我必须输入我想获取信息的城市,程序会给我那个城市的信息

标签: pythonarraysrecord

解决方案


您可以像这样按相关城市名称过滤 city_array (您可以在此处阅读列表理解

relevant_cities = [c for c in city_array if c[0] == city]

现在,related_cities 将是具有城市等于用户输入的所有记录的列表。您现在可以检查此列表是否为空,并根据需要执行任何操作。


推荐阅读