我如何查找并显示包含使用 python 中的算法找到的一段数据的记录

How can i find and display a record that contains a piece of data found using an algorithm in 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)


  min = city_array[2]
  for i in range(len(city_array)):
    if min < city_array[i]:
      min = city_array[i]

  relevant_cities = [c for c in city_array if c[2] == min]
  print(relevant_cities[min])

main_program()

您的 city_records 不仅仅是一个列表,它是一个列表的列表。所以不要写 min = city_array[2],而是写 min = city_array[0][2]
因为我们将 0 索引分配为最小值,所以我们应该从 1 索引开始循环。

min = city_array[0][2]
for i in range(1,len(city_array)):
    if min > city_array[i][2]:
        min = city_array[i][2]

relevant_cities = [c for c in city_array if c[2] == min]
print(relevant_cities)

此外,在函数 populateRecords 的 while 循环中,您忘记将字符串转换为浮点数 population=input()-> population=float(input())