这是我的代码读取一个文件与电影标题和他们的评级,我需要读取该文件,并根据他们的评级排序。我使用的是Python代码。
该文件如下所示:
《哈利波特与阿兹卡班的囚徒》7.8《指环王:双子塔》8.7《蜘蛛侠》7.3《爱丽丝梦游仙境》6.5《好心的恐龙》6.7《功夫熊猫》7.6
filename =("movie_ratings.txt")
def ratings_sort(array):
with open (filename) as f:
for pair in f:
title.append(pair.strip())
for index in f:
value = array[index]
i = index-1
while i>=0:
if value < array[i]:
array[i+1]=array[i]
array[i]=value
i = i-1
else:
break
title = list ()
rating = list('.')
filename =("movie_ratings.txt")
with open (filename) as f:
for pair in f:
title.append(pair.strip())
title.sort()
ratings_sort = sorted(title, key=lambda rating:rating[2])
print ("Old List :\n",title)
print('\n')
print("New List :\n" ,ratings_sort)这是我的结果
老名单:《爱丽丝梦游仙境》6.5,《哈利波特与阿兹卡班的囚徒》7.8,《功夫熊猫》7.6,《指环王:双子塔8.7》,《蜘蛛侠》7.3,《好心的恐龙6.7》
最新榜单:“好恐龙,6.7”;“爱丽丝漫游仙境”,6.5;“蜘蛛侠”,7.3;“功夫熊猫”,7.6;“哈利波特与阿兹卡班的囚犯”,7.8;“指环王:双子塔”,8.7。
发布于 2018-03-31 11:48:01
问题是"for x in file“循环从文件中读取行,因此title数组将文件中的行作为字符串包含。因此,sorted的key参数接收这些字符串并返回每个字符串的第三个字符(rating[2]);请注意,“新列表”实际上是按第三个字符- e,i,i,n,r,r排序的。要解决这个问题,可以将文件行解析为形式为(标题,评级)的元组,并将这些元组存储在数组中。然后,按评级排序就像从sorted的key参数的元组中获取评级一样简单。
然而,在我看来,您似乎希望实现自己的排序,而不是使用内置的sorted。看起来你打算实现一个插入排序,当你在这里发帖时,缩进变得一团糟。该函数具有不解析文件行的相同类型的问题,您需要在第二个循环中迭代array的数值索引,而不是f的行。通过将if移动到while条件中,并且只分配比较评级的最终位置,而不是掉期,也可以稍微改进一下逻辑。
from collections import namedtuple
def ratings_sort(movies):
for index in range(1, len(movies)):
movie = movies[index]
i = index-1
while i>=0 and movie.rating < movies[i].rating:
movies[i+1] = movies[i]
i -= 1
movies[i+1] = movie
filename = "movie_ratings.txt"
Movie = namedtuple("Movie", "title rating")
movies = list()
with open(filename) as f:
for line in f:
part = line.partition(",") # gives a tuple: ("movie title", ",", "rating)
movies.append(Movie(title=part[0].strip(), rating=float(part[2])))
print("Old List:\n", movies, "\n")
# Sort using sorted
sorted_movies = sorted(movies, key=lambda movie:movie.rating)
# Sort using ratings_sort (modifies movies array unlike sorted)
ratings_sort(movies)
print("New List (using sorted):\n", sorted_movies, "\n")
print("New List (using ratings_sort):\n", movies, "\n")请注意,为了清楚起见,我重命名了一些变量并使用了namedtuple。此外,我将文件读数从ratings_sort中移出,以便可以将其与sorted进行比较。
发布于 2018-03-31 17:03:30
让我们一步一步地解决您的问题:
所以你的问题有两个部分:
对其进行排序
对于第一部分,我尝试了两种方法:
第一种方法,使用手动生成器方法,
首先让我们打开 :
with open('dsda') as f:
data=[line.strip().split() for line in f if line!='\n'][0]为此,我需要浮点数是数字,但数字只支持整数,所以我想出了这样的东西:
def isfloat(point):
try:
float(point)
return True
except ValueError:
return False现在让我们使用生成器方法来获得适当形式的数据:
def generator_approach(data_):
storage=[]
flag=True
for word in data_:
storage.append(word)
if isfloat(word)==True:
yield storage
storage=[]
closure_ = generator_approach(data)
print(list(closure_))输出:
[['Harry', 'Potter', 'and', 'the', 'Prisoner', 'of', 'Azkaban', ',', '7.8'], ['Lord', 'of', 'the', 'Rings:', 'The', 'Two', 'Towers', ',', '8.7'], ['Spider', 'Man', ',', '7.3'], ['Alice', 'in', 'Wonderland', ',', '6.5'], ['The', 'Good', 'Dinosaur', ',', '6.7'], ['Kung', 'Fu', 'Panda', ',', '7.6']]现在让我们尝试第二种方法,即方法:
import re
pattern=r'\w.+?[0-9.]+'
with open('dsda') as f:
for line in f:
data_r=[line1.split() for line1 in re.findall(pattern,line)]输出:
[['Harry', 'Potter', 'and', 'the', 'Prisoner', 'of', 'Azkaban', ',', '7.8'], ['Lord', 'of', 'the', 'Rings:', 'The', 'Two', 'Towers', ',', '8.7'], ['Spider', 'Man', ',', '7.3'], ['Alice', 'in', 'Wonderland', ',', '6.5'], ['The', 'Good', 'Dinosaur', ',', '6.7'], ['Kung', 'Fu', 'Panda', ',', '7.6']]正如您所看到的,两种方法的输出是相同的,现在根据评级对它们进行排序并不是什么大问题:
print(sorted(data_r,key=lambda x:float(x[-1])))输出:
[['Alice', 'in', 'Wonderland', ',', '6.5'], ['The', 'Good', 'Dinosaur', ',', '6.7'], ['Spider', 'Man', ',', '7.3'], ['Kung', 'Fu', 'Panda', ',', '7.6'], ['Harry', 'Potter', 'and', 'the', 'Prisoner', 'of', 'Azkaban', ',', '7.8'], ['Lord', 'of', 'the', 'Rings:', 'The', 'Two', 'Towers', ',', '8.7']]https://stackoverflow.com/questions/49582928
复制相似问题