Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过调用元组的一个元素来索引元组_Python_List_For Loop_Tuples - Fatal编程技术网

Python 通过调用元组的一个元素来索引元组

Python 通过调用元组的一个元素来索引元组,python,list,for-loop,tuples,Python,List,For Loop,Tuples,我正试图写一个函数来接受 包含partygoers名称及其优先级和 可以获取它的最大人数。我目前正试图根据元组的一个元素将元组按升序排列 我有一个列表或元组: alist =[('Carlos', 1), ('Gretchen', 8), ('Abby', 6),('Sam', 4)] 到目前为止,我已经按照代码的顺序列出了所有数字: def party_time(alist,maxnum): newlist = [] finallist=[] while l

我正试图写一个函数来接受

  • 包含partygoers名称及其优先级和
  • 可以获取它的最大人数。我目前正试图根据元组的一个元素将元组按升序排列 我有一个列表或元组:

     alist =[('Carlos', 1), ('Gretchen', 8), ('Abby', 6),('Sam', 4)]
    
    到目前为止,我已经按照代码的顺序列出了所有数字:

     def party_time(alist,maxnum):
         newlist = []
         finallist=[]
         while len(finallist) < maxnum:
            for tup in alist:
                rank = tup[1]
                newlist.append(rank)
            newlist.sort()
    
     newlist = [1,4,6,8]
    
    def party\u时间(列表,最大值):
    新列表=[]
    finallist=[]
    而len(finallist)
    有没有一种方法可以使用for循环遍历
    newlist
    并使用
    newlist
    中的数字对元组进行索引?或者它只是索引元组中数字的位置吗?

    这应该可以做到:

    def party_time(alist, maxnum):
        sorted_list = sorted(alist, key=lambda p: p[1], reverse=True)
        return sorted_list[:maxnum]
    

    sorted(alist,key=lambda x:x[1])
    应该对项目进行排序。您可能还需要反向操作。可能的重复也请注意,您的代码进入了一个无限循环。