【问题标题】:Python - Indexing, comparing and appendingPython - 索引、比较和追加
【发布时间】:2015-04-07 18:22:58
【问题描述】:

如您所知,我在命名问题的标题时遇到了困难。无论如何,将问题置于某些上下文中:我有一个高分文本文件,数据已放入列表中。每个人的分数已经过排序,所以他们现在从低到高排序。

data = [['Stuart', 'got', 'a', 'highscore', 'of:', '92'], [ 'Steve', 
         'got', 'a', 'highscore', 'of:', '53'], ['Andrew', 'got', 'a', 
         'highscore', 'of:', '73'], ['Luke', 'got', 'a', 'highscore', 
         'of:', '1'], [ 'Shaney', 'got', 'a', 'highscore', 'of:', '77'], 
        ['Robert', 'got', 'a', 'highscore', 'of:', '33'], ['Moley', 
         'got', 'a', 'highscore', 'of:', '6'], [ 'Kev', 'got', 'a', 
         'highscore', 'of', '2322']]
numbers = [1, 6, 33, 53, 73, 77, 92, 2322]
temp = []

我的目标是创建一个名为“temp”的列表,其中包含 有序数据。 “有序数据”将是原始日期,但经过安排,['Luke', 'got', 'a', 'highscore', 'of:', '1'] 将位于“临时”列表的开头。

像往常一样,任何可以帮助我的反馈都将不胜感激。

【问题讨论】:

    标签: python list indexing int append


    【解决方案1】:
    temp = sorted(data, key= lambda s: int(s[-1]))
    

    我认为这会起作用,但我没有测试过

    【讨论】:

    • 只需将其转换为整数。非常感谢您的回复,我真的已经很长时间试图弄清楚了,非常感谢您。
    【解决方案2】:

    确保转换为 int 的排序,否则“100000”将排在“2”之前:

     print(sorted(data,key=lambda x:int(x[-1])))
    

    如果您真的想将最后一个条目作为 int 存储在输出列表中:

    temp =  [x[:-1]+[int(x[-1])] for x in sorted(data,key=lambda x:int(x[-1]))]
    

    【讨论】:

    • @BhargavRao,两者都添加了
    • @BhargavRao LMAO。我也在想同样的事情......但我不想说......无论如何,+1以获得完整的答案。
    • @BhargavRao,幸运的是这是一个编程网站,而不是拼写网站;)
    • @PadraicCunningham 你应该在english.stackexchange.com 上……你会被像地狱一样被否决
    • 仅仅因为回答问题超出了要求的范围并且解释得很好而被授予答案。感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 2019-05-28
    • 2020-04-05
    相关资源
    最近更新 更多