[英]Python - Ordering a list numerically
I have a list of file names in this form: 我有一个这种形式的文件名列表:
L='csv (2).zip', 'csv (5).zip', 'csv (1).zip', etc...
what is the easiest way to order this data numerically? 以数字方式订购此数据的最简单方法是什么? So that I have: 所以我有:
csv (1).zip, csv (2).zip, csv (5).zip, ...
You can get the number within the parentheses, like this x.index("(") + 1 : x.rindex(")")
. 您可以在括号内获取数字,例如x.index("(") + 1 : x.rindex(")")
。 So, we apply that on each and every element and convert that to a number 因此,我们将其应用于每个元素并将其转换为数字
my_list = ['csv (2).zip', 'csv (5).zip', 'csv (1).zip']
print(sorted(my_list, key = lambda x: int(x[x.index("(") + 1 : x.rindex(")")])))
# ['csv (1).zip', 'csv (2).zip', 'csv (5).zip']
How could you use this to sort an array in python, for example, if I wanted to print the highest and lowest mark from this code. 你怎么能用它来在python中对数组进行排序,例如,如果我想打印这段代码中的最高和最低标记。
print("Student Grades" ) #Title of the program
studentGrades = [] # Creating an array to hold the grades
for i in range(6):
grade = float(input("Please Enter percentage: "))
studentGrades.append(grade)
grade = str(grade)
saveFile = open('studentGrades.txt', 'a')
saveFile.write(grade)
saveFile.close()
print(studentGrades)
gradeTotal = 0
for i in range(len(studentGrades)):
gradeTotal = gradeTotal + studentGrades[i]
gradeAverage = gradeTotal/6
print"Your average grade is", gradeAverage, "%"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.