zoukankan      html  css  js  c++  java
  • 相同的字母后面的数字加在一起,按字母的顺序输出

    按照要求实现如下要求效果
    4.假如现在有个文本,格式如下:
    a  1
    b  3
    c  2
    d  7
    b  5
    a  3 
    g  2
    f  6
    d  9
    即左边是随机字母,右边是随机数字,要求写个脚本使其输出格式为:
    a  4
    b  8
    c  2
    d  16
    f  6
    g  2
    即将相同的字母后面的数字加在一起,按字母的顺序输出。
    1. [root@LAMP-2 ~]# cat 98.txt
      a  1
      b  3
      c  2
      d  7
      b  5
      a  3 
      g  2
      f  6
      d  9
      [root@LAMP-2 ~]# awk '{if(!a[$1]) b[++t]=$1;a[$1]+=$2;}END{for(i=1;i<=t;i++) print b[i],a[b[i]]}' 98.txt |sort
      a 4
      b 8
      c 2
      d 16
      f 6
      g 2
      [root@LAMP-2 ~]# awk '{a[$1]+=$2;}END{for(i in a){{print i" "a[i];}}}' 98.txt
      a 4
      b 8
      c 2
      d 16
      f 6
      g 2
      [root@LAMP-2 ~]#
    2. 用python的方法
    [root@LAMP-2 ~]# cat 98.txt 
    a  1
    b  3
    c  2
    d  7
    b  5
    a  3 
    g  2
    f  6
    d  9
    [root@LAMP-2 ~]# cat 98.py 
    with open('./98.txt','rt') as f:
            dic={}
            for line in f.readlines():
                    a,b=line.split()
                    if a in dic.keys():
                            dic[a] +=int(b)
                    else:
                            dic.update({a:int(b)})
            for key,val in dic.items():
                    print(key,val)
    [root@LAMP-2 ~]# 
  • 相关阅读:
    chlick 在 blur 之后触发
    屏蔽运营商广告
    script标签清除缓存
    http-equiv 详解
    jqLite
    js 时间戳和转换-转载
    JS数组的常用方法
    js 前端实现文件流下载的几种方式
    解决兼容性的库
    移动端兼容性问题
  • 原文地址:https://www.cnblogs.com/wangwei325/p/5088644.html
Copyright © 2011-2022 走看看