这就是我现在拥有的
def BabyNames():
RFile = open("boys.dat.txt","r")
OFile = open("girls.dat.txt","r")
babyNameLst = []
result=[]
for line in RFile:
line = line.strip()
name,count= line.split(",")
name= name.strip()
New = (count,name)
babyNameLst.append(New)
for line in OFile:
line= line.strip()
name,count = line.split(",")
name=name.strip()
New = (count,name)
babyNameLst.append(New)
sorted_Nums = sorted(babyNameLst, reverse= True)
print(sorted_Nums[:100])
示例 boys.dat.txt :
Jacob ,204760
Michael ,187948
Joshua ,173395
Matthew ,168437
Andrew ,151667
Christopher ,148897
Daniel ,145989
Joseph ,144904
Ethan ,140215
Nicholas ,139296
William ,138425
Anthony ,136813
David ,129579
Ryan ,129284
Tyler ,126685
示例 girls.dat.txt :
Emily ,170901
Madison ,142410
Emma ,125605
Hannah ,124651
Abigail ,105519
Olivia ,104454
Ashley ,103995
Samantha ,101188
Alexis ,100782
Sarah ,96907
Elizabeth ,96682
Isabella ,88941
Alyssa ,85267
Grace ,83188
Lauren ,77841
Taylor ,76907
Jessica ,76093
Brianna ,74945
Kayla ,73756
这些是名称和使用次数的计数。我需要使用计数找出这些男孩和女孩名字中的前100名。我该怎么做?计数告诉我选择名字的次数,需要最多前100个名字。
它将按顺序进行: 204740雅各布 187948迈克尔 173395约书亚 170901艾米莉 168437安德鲁 等等...
答案 0 :(得分:1)
只需将您的排序更改为
sorted(babyNameLst, key=lambda tup: int(tup[0]), reverse=True)
还有一点注意:根据PEP 8,对于变量名,下划线应仅用于:baby_name_list。允许使用Camlecase类
答案 1 :(得分:0)
您可以使用pandas.read_csv()轻松地做到这一点,即
import pandas as pd
boys = pd.read_csv("boys.txt", names=['names','births'])
print(boys)
Jacob 204760
0 Michael 187948
1 Joshua 173395
2 Matthew 168437
3 Andrew 151667
4 Christopher 148897
5 Daniel 145989
6 Joseph 144904
7 Ethan 140215
8 Nicholas 139296
9 William 138425
10 Anthony 136813
11 David 129579
12 Ryan 129284
13 Tyler 126685
如果需要打印前5个,可以使用:
print(boys.head(5))
names births
0 Jacob 204760
1 Michael 187948
2 Joshua 173395
3 Matthew 168437
4 Andrew 151667
我需要一个男孩和一个女孩在一起
concat
这两个数据帧,即:
b = pd.read_csv("boys.txt", names=['names','births'])
g = pd.read_csv("girls.txt", names=['names','births'])
x = pd.concat([b, g]).reset_index(drop=True)
print(x)
names births
0 Jacob 204760
1 Michael 187948
2 Joshua 173395
3 Matthew 168437
4 Andrew 151667
5 Christopher 148897
6 Daniel 145989
7 Joseph 144904
8 Ethan 140215
9 Nicholas 139296
10 William 138425
11 Anthony 136813
12 David 129579
13 Ryan 129284
14 Tyler 126685
15 Emily 170901
...
答案 2 :(得分:0)
我希望女孩的名单和男孩的名单分开排序(就像我所看到的那样)
因此,您需要从两个列表中获取排序后的数组。
您要查找的内容与合并排序中的合并算法非常相似。
假设两个数组都按升序排序,我们希望结果数组保持相同的顺序。将两个数组A [0..m-1]和B [0..n-1]合并为数组C [0..m + n-1]的算法如下:
algorithm merge(A, B) is
inputs A, B : list
returns list
C := new empty list
while A is not empty and B is not empty do
if head(A) ≤ head(B) then
append head(A) to C
drop the head of A
else
append head(B) to C
drop the head of B
// By now, either A or B is empty. It remains to empty the other input list.
while A is not empty do
append head(A) to C
drop the head of A
while B is not empty do
append head(B) to C
drop the head of B
return C
这是合并算法的伪代码。希望有道理。干杯!!!