Python检查列表中的重复项并将重复项添加到一起,以使用求和值更新列表

2024-09-30 03:24:49 发布

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

我的问题的目的是阅读这样一篇帖子:

([
{
    'title': 'Invade Manhatten, anyone?',
    'tags': ['world-domination', 'hangout'],
    'posts': [
        {
            'author': 'Mr. Sinister',
            'content': "I'm thinking 9 pm?",
            'upvotes': 2,
        },
        {
            'author': 'Mystique',
            'content': "Sounds fun!",
            'upvotes': 0,
        },
        {
            'author': 'Magneto',
            'content': "I'm in!",
            'upvotes': 0,
        },
    ],
}

]))

并创建一个定义来输出:

[('Mr. Sinister', '2', 'Cautioiusly Evil'), ('Magneto', '0', 'Insignificantly Evil'), ('Mystique', '0', 'Insignificantly Evil')]

其中列表按最高投票数到最低投票数排序,并按字母顺序断开连接。你知道吗

然而,当我看到这条线索时:

([
{
    'title': 'Invade Manhatten, anyone?',
    'tags': ['world-domination', 'hangout'],
    'posts': [
        {
            'author': 'Mr. Sinister',
            'content': "I'm thinking 9 pm?",
            'upvotes': 2,
        },
        {
            'author': 'Mr. Sinister',
            'content': "Sounds fun!",
            'upvotes': 0,
        },
        {
            'author': 'Mr. Sinister',
            'content': "I'm in!",
            'upvotes': 0,
        },
    ],
}

]))

在作者多次发布的地方,我的程序输出:

[('Mr. Sinister', '2', 'Cautioiusly Evil'), ('Mr. Sinister', '0', 'Insignificantly Evil'), ('Mr. Sinister', '0', 'Insignificantly Evil')]

我的程序打印每个帖子,而不是像这样组合结果:

[('Mr. Sinister', 2, 'Cautiously Evil')]

只是澄清一下,如果线索是:

([
{
    'title': 'Invade Manhatten, anyone?',
    'tags': ['world-domination', 'hangout'],
    'posts': [
        {
            'author': 'Mr. Sinister',
            'content': "I'm thinking 9 pm?",
            'upvotes': 2,
        },
        {
            'author': 'Loki',
            'content': "Sounds fun!",
            'upvotes': 2,
        },
        {
            'author': 'Mr. Sinister',
            'content': "I'm in!",
            'upvotes': 2,
        },
        {
            'author': 'Loki',
            'content': "I'm in it!",
            'upvotes': 20,
        },

    ],
}

]))

它应该输入:

[('Loki', 22, 'Justifiably Evil'), ('Mr. Sinister', 4, 'Cautiously Evil')]

我的代码如下:

  def author_rankings(thread_list):
# TODO: Determine (author, upvotes, ranking) over all threads.
counterA = 0
counterB=2

listA = []
Final = []
Double = {}
for i in thread_list[0]['posts']:
    for ii in i:
        if ii == 'content':
            null = 1
        else:
            b = str(i[ii])
            if b in Double:
              Double[b]
            a = b
            if a.isdigit():
              a = int(a)
            listA.append(a)
bel=[]
for qq in listA:
    if counterA == counterB:
        bel = []
        counterB+=2
    if counterA%2 ==0:
         bel.append(qq)
         counterA+=1
    else:
       bel.append(qq)
       qq = int(qq)
       if qq == 0:
           bel.append('Insignificantly Evil')

     elif qq < 20:
          bel.append('Cautiously Evil')


     elif qq < 100:
          bel.append('Justifiably Evil')

     elif qq < 500:
           bel.append('Wickedly Evil')

     elif qq >= 500:
          bel.append('Diabolically Evil')

     counterA+=1



     tuuple = tuple(bel)
     Final.append(tuuple)



Final.sort()      

Final.sort(key=lambda tup: -tup[1])

我知道我的代码有点不太懂/难读。很抱歉给您带来不便。你知道吗

谢谢你!你知道吗


Tags: inifcontentauthorfinalqqpostsevil
3条回答

这段代码可以工作,希望它可读性足够好,这样您就可以修改它了

x = in[0]  # returns a dict from your input

for post in x.get('posts'):
        author = post.get('author')
        if author not in d.keys():
            d[author] = post
        else:
            d.get('author')['upvotes'] += post.get('upvotes')

这将返回一个没有重复作者的dict,如果已经存在,则不会更新分数。你知道吗

我在你的数据上试过了,效果不错

d {'Mr. Sinister': {'content': "I'm thinking 9 pm?", 'upvotes': 2, 'author': 'Mr. Sinister'}}

这可能有用,它忽略了内容(如果需要也可以添加),只需要增加投票和作者。它还使用字典而不是列表:

authors = dict()

for post in x[0]['posts']:
    try:
        authors[post['author']] += post['upvotes']

    except KeyError:
        authors[post['author']] = post['upvotes']

for k, upvotes in authors.iteritems():
    if upvotes == 0:
        authors[k] = (upvotes, "Insignificantly Evil")

    elif upvotes < 20:
        authors[k] = (upvotes, "Cautioiusly Evil")

    elif upvotes < 100:
        authors[k] = (upvotes, "Justifiably Evil")

    elif upvotes <= 500:
        authors[k] = (upvotes, "Wickedly Evil")

    elif upvotes > 500:
        authors[k] = (upvotes, "Diabolically Evil")

print authors

输出:

{'Mr. Sinister': (2, 'Cautioiusly Evil')}

以及:

{'Mr. Sinister': (4, 'Cautioiusly Evil'), 'Loki': (22, 'Justifiably Evil')}

对于第二个例子。你知道吗

我不明白你在问什么,因为逻辑不太清楚。你知道吗

但是,可以这样进行聚合:

some_pages = [
        {
            'title': 'Invade Manhatten, anyone?',
            'tags': ['world-domination', 'hangout'],
            'posts': [
                {
                    'author': 'Mr. Sinister',
                    'content': "I'm thinking 9 pm?",
                    'upvotes': 2,
                },
                {
                    'author': 'Mr. Sinister',
                    'content': "Sounds fun!",
                    'upvotes': 0,
                },
                {
                    'author': 'Mr. Sinister',
                    'content': "I'm in!",
                    'upvotes': 0,
                },
            ],
        }
    ]

author_aggregation = {}
for pages in some_pages:
    for post in pages.get('posts', []):
        a = post.get('author')
        v = post.get('upvotes')
        c = post.get('content')
        if a in author_aggregation:
            author_aggregation.update({a: {'upvotes': author_aggregation[a]['upvotes'] += v, 'content': author_aggregation[a]['content'].append(c)}})
        else:
            author_aggregation[a] = {'upvotes': v, 'content': [c]}

相关:

相关问题 更多 >

    热门问题