?如何制作二维矩阵

2024-04-19 23:08:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典和一个元组

 students = { 0: "Nynke", 1: "Lolle", 2: "Jikke", 3: "Popke", 4: "Teake", 5:
"Lieuwe", 6: "Tsjabbe", 7: "Klaske", 8: "Ypke", 9: "Lobke"}

friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5), (5,
6), (5, 7), (6, 8), (7, 8), (8, 9)]

我首先要做的是一个二维矩阵,其中每个学生都有一个和他们朋友的列表,比如:[[1,2],[0,2,3],…,[8]]

第二件事是我必须根据我必须打印的朋友数量对列表进行排序,比如:[(9,1),(0,2),…,(8,3)]。 数字9只有一个朋友,数字0有两个朋友等等。。。你知道吗

我的代码:

for i in students:
    for x in friendships:
        if students[i] == friendships(x):
            new_list.append(x)
    print(i)

Tags: in列表for字典朋友数字元组students
1条回答
网友
1楼 · 发布于 2024-04-19 23:08:07

我不能百分之百肯定我完全理解你的意图,所以如果我有错误的想法,请纠正我。但我是这么想的

对于第一个,你可以尝试创建一个字典来存储每一个友谊

all_friends = {}
for f in friendships:
   if f[0] in all_friends:
      all_friends[f[0]] = all_friends[f[0]] + [f[1]]
   else:
      all_friends[f[0]] = [f[1]]

然后你会想得到这个字典值的列表,这就是你的2d矩阵:

all_friends.values()

对于第二个问题,你首先需要记录每个人有多少友谊,试试字典

friendships_dict = {}
for f in friendships:
   if f[0] in friendships_dict{}:
      friendships_dict[f[0]] = friendships_dict[f[0]] + 1
   else:
      friendships_dict[f[0]] = 1

然后,您需要将其作为可以排序的元组列表:

friends_list = [(f1, f2) for f1, f2 in friendships_dict.iteritems()]

sorted_friends_list = sorted(friends_list, key=lambda x: x[1])

编辑

既然我已经更好地理解了你问题的第一部分,那就让我来提出一个解决办法。你知道吗

您仍然需要我包含的第一段代码:

all_friends = {}
for f in friendships:
   if f[0] in all_friends:
      all_friends[f[0]] = all_friends[f[0]] + [f[1]]
   else:
      all_friends[f[0]] = [f[1]]

然后添加以下内容:

matrix = [] 
for key in sorted(all_friends.iterkeys()):
    matrix.append(all_friends[key])

matrix将是你想要的

相关问题 更多 >