简体   繁体   English

Python - 在包含字符串和数字的列表中订购数字值

[英]Python - Ordering Number Values in a List Containing Strings and Numbers

I have Created a list which contains all of the information from a scores file in python. 我创建了一个列表,其中包含python中score文件中的所有信息。

The scores .txt file: 得分.txt文件:

Dan Danson,9,6,1
John Johnson,5,7,10
Mike Mikeson,10,7,6

I did this to get the information from the .txt file into a 2d list: 我这样做是为了将.txt文件中的信息转换为2d列表:

f = open(filename, 'r')
lines = f.readlines()
f.close()

scores = []
for line in lines: #Loads lines into a 2d list
    currentline = line.strip('\n').split(",")
    scores.append(currentline)

Now I have this list: 现在我有这个清单:

[['Dan Danson', '1', '6', '9'], ['John Johnson', '5', '7', '10'], ['Mike Mikeson', '10', '7', '6']]

From this list I would like to sort the numbers in the list so that they are ordered from highest to lowest so i get a list that looks like this: 从这个列表中我想对列表中的数字进行排序,以便从最高到最低排序,所以我得到一个如下所示的列表:

[['Dan Danson', '9', '6', '1'], ['John Johnson', '10', '7', '5'], ['Mike Mikeson', '10', '7', '6']]

Finally I want to be able to print the list ordered highest to lowest. 最后,我希望能够打印从最高到最低排序的列表。

Mike Mikeson,10,7,6
John Johnson,10,7,5
Dan Danson,9,6,1

Using sorted with int as a key function: 采用sortedint作为关键功能:

>>> rows = [
...     ['Dan Danson', '1', '6', '9'],
...     ['John Johnson', '5', '7', '10'],
...     ['Mike Mikeson', '10', '7', '6'],
... ]
>>>
>>> rows = [row[:1] + sorted(row[1:], key=int, reverse=True) for row in rows]
>>> sorted(rows, key=lambda row: sum(map(int, row[1:])), reverse=True)
[['Mike Mikeson', '10', '7', '6'],
 ['John Johnson', '10', '7', '5'],
 ['Dan Danson', '9', '6', '1']]
  • sorted(row[1:], ..) : separate number values and sort. sorted(row[1:], ..) :单独的数字值和排序。
  • row[:1] : name as a list, alternatively you can use [row[0]] . row[:1] :name作为列表,或者你可以使用[row[0]] Should be a list to be concatenated to a list of number strings. 应该是要连接到数字字符串列表的列表。

Using sorted and map to cast strings to ints: 使用sortedmap将字符串转换为整数:

>>> l = [['Dan Danson', '9', '6', '1'], ['John Johnson', '10', '7', '5'], ['Mike Mikeson', '10', '7', '6']]
>>> for e in l:
...     print(e[0], *sorted(list(map(int, e[1:]))))
...     
... 
Dan Danson 1 6 9
John Johnson 5 7 10
Mike Mikeson 6 7 10

You can approach the problem this way as well. 您也可以通过这种方式解决问题。 I first convert all grades into integer type so that I can keep my lambda function clean. 我首先将所有等级转换为整数类型,以便我可以保持我的lambda函数清洁。 I could have done the conversion in lambda function but it does not fancy me much. 我本可以在lambda函数中完成转换,但它并不像我这么想。

You can see splitting the each problem into different module, gives re-usability. 您可以看到将每个问题拆分为不同的模块,从而提供可重用性。

test = [['Dan Danson', '1', '6', '9'], ["Karthikeyan", 10, 10, 10], ['John Johnson', '5', '7', '10'], ['Mike Mikeson', '10', '7', '6']]

def covert_to_integer(test):
    """
    Coverting all grades into integer type
    """
    for outer_index, item in enumerate(test):
        for inner_index, element in enumerate(item[1:], 1):
            test[outer_index][inner_index] = int(element)
    return sorting_by_sum(test)

def sorting_by_sum(test):
    """
    Sorting the records by sum of the grades. 
    """
    return sorted(test, key=lambda record: record[1]\
                                   + record[2] \
                                   + record[3], reverse=True)

if __name__ == "__main__":
    print covert_to_integer(test)

You can even use the sum method of list in lambda function. 你甚至可以在lambda函数中使用list的sum方法。 Like this: 像这样:

return sorted(test, key=lambda record: sum(record[1:])\
                                   ,reverse=True)

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

相关问题 按 Python 中字符串中的数字对列表开头包含数字的字符串列表进行排序 - Sort a list of strings containing numbers at the start of the list by the numbers in the strings in Python 从包含 python 中的字符串和数字的列表中获取最小值和最大值,然后用这些值替换字符串? - Get minimum and maximum values from a list containing both strings and numbers in python and then replace the strings with these values? 在python中的字符串列表中用数字分隔值 - Segregating values with numbers in a list of strings in python 在Python中排序带空格的字符串列表 - Ordering a List of Strings with spaces in Python 比较Python中包含数字的字符串 - Comparing strings containing numbers in Python Python:在包含区间的列表中查找字符串并用其中的每个数字替换该区间 - Python: Finding strings in a list containing an interval and replacing this interval by every number in it 在Python中将数字列表转换为包含实际值的字符串 - Convert list of numbers into a string in Python containing the actual values 如何比较列表中包含数字的字符串? - How to compare strings containing numbers in a list? 如何在Python中用数字和字符串查找列表中的最大数字? - How to find the maximum number in a list with numbers and strings in Python? Python:包含字符串子列表的列表 - Python: List containing sublist of strings
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM