Home  >  Q&A  >  body text

python中遍历列表的合并问题

针对爬虫结果的列表,应当如何处理才能进行合并,试过一些方法都不是预期的效果
我希望的效果是将:
【‘犯罪’】
【‘犯罪’,‘剧情’】
……
合并成:
【‘犯罪’,‘犯罪’,‘剧情’……】
最终目的是进行出现频率的统计。
谢谢指点!

黄舟黄舟2740 days ago674

reply all(5)I'll reply

  • PHPz

    PHPz2017-04-18 10:22:40

    Put count_times=[] outside the big loop (the first loop), and then count

    print dict([(i,count_times.count(i)) for i in set(count_times)])

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:22:40

    If your goal is to count the frequency of occurrence, you can use Counter in collections
    As shown in the picture

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:22:40

    Just use a dictionary to count

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:22:40

    In [1]: b, a = {}, [1, 2, 3, 4, 5, 6]
    
    In [2]: [b.update({key: b[key] + 1}) if key in b.keys() else b.update({key: 1})  for key in a]
    Out[2]: [None, None, None, None, None, None]
    
    In [3]: b
    Out[3]: {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:22:40

    Counter can also display the list after statistics

    reply
    0
  • Cancelreply