简体   繁体   English

从数字列表中删除最小元素,其中每个数字都与年份列表相关联

[英]Remove the smallest element from a list of numbers where each numbers are associated to a year list

1. num_list =       [   5,    1,    3,    2,    4,   56,   19,    8,    1,    7]
2. year_list = [2020, 2021, 2019, 2020, 2019, 2017, 2017, 2020, 2020, 2021]
3. year = 2020

#I want to remove number 1 from year 2020. #我想从 2020 年删除数字 1。

#This is what i have so far... #这是我目前所拥有的...

num_list =       [   5,    1,    3,    2,    4,   56,   19,    8,    1,    7]
year_list = [2020, 2021, 2019, 2020, 2019, 2017, 2017, 2020, 2020, 2021]
year = 2020
batch_list=[]
for n_list,y_list in zip(num_list,year_list):   
     if(y_list==year):
        batch_list.append(n_list)

batch_number=min(batch_list)

batch_index= num_list.index(batch_number)
num_list.remove(batch_number)
del year_list[batch_index]
num = [5,1,3,2,4,56,19,8,1,7]
year_list=[2020,2021,2019,2020,2019,2017,2017,2020,2020,2021]
year=2020

stored = []
for j in range(0, len(year_list)):
    if (year_list[j] == year):
        stored.append((num[j], j))
        
stored.sort()

lowest_num_for_year = stored[:1]

num.pop(lowest_num_for_year[0][1])
year_list.pop(lowest_num_for_year[0][1])

print(year)
print(lowest_num_for_year[0][0])
print(num)

It can also be done this way, using the enumerate and zip functions..也可以通过这种方式完成,使用 enumerate 和 zip 函数。

num_list = [5,1,3,2,4,56,19,8,1,7]
year_list=[2020,2021,2019,2020,2019,2017,2017,2020,2020,2021]
year=2020
batch_list=[]
for index, (n_list, y_list) in enumerate(zip(num_list, year_list)):
    if(y_list==year):
         batch_list.append((num_list,index))

batch_list.sort() # sort the list of sets in acending order
lowest_num_for_year = batch_list[:1] # get first set of sorted set
batch_number=lowest_num_for_year[0][0] # get the element from set
batch_index=lowest_num_for_year[0][1] # get the index of the set

del num_list[batch_index]   #delete the specific number
del year_list[batch_index]   # delete the specific year
                

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM