如何计算大型数组中字符串的某些元素?

时间:2018-09-16 21:25:14

标签: python arrays string count

我不确定是否可行,但是我有一个包含日期的超大数组

| size | points |
|------|--------|
| 10   | 10     |
| 20   | 9      |
| 30   | 8      |
| 40   | 7      |
| 50   | 6      |
| 60   | 5      |
| 70   | 4      |
| 80   | 3      |
| 90   | 2      |
| 100  | 1      |

我试图找到是否有一种方法可以计算数组中天数和月数的频率。在这种情况下,我尝试将字符串计算为几个月或几天的缩写(例如Fri,Mon,Apr,Jul)

2 个答案:

答案 0 :(得分:1)

您可以在“收藏”模块中使用Counter()

from collections import Counter

a = ['Fri, 19 Aug 2011 19:28:17 -0000', 
     'Fri, 09 June 2017 11:11:11 -0000', 
     'Wed, 05 Feb 2012 11:00:00 -0000']

# this generator splits the dates into words, and cleans word from "".,;-:" characters:
#  ['Fri', '19', 'Aug', '2011', '19:28:17', '0000', 'Fri', '09', 'June',
#   '2017', '11:11:11', '0000', 'Wed', '05', 'Feb', '2012', '11:00:00', '0000']
# and feeds it to counting:   
c = Counter( (x.strip().strip(".,;-:") for word in a for x in word.split() ))

for key in c:
    if key.isalpha():
        print(key, c[key])

if仅打印来自计数器的纯“字母”键,而不打印数字:

Fri 2 
Aug 1
June 1
Wed 1
Feb 1

日期名称和月份名称是日期中唯一的pure isalpha() parts

完整的c输出:

Counter({'0000': 3, 'Fri': 2, '19': 1, 'Aug': 1, '2011': 1, 
         '19:28:17': 1, '09': 1, 'June': 1, '2017': 1, '11:11:11': 1, 
         'Wed': 1, '05': 1, 'Feb': 1, '2012': 1, '11:00:00': 1})

@AzatIbrakov评论的改进:

c = Counter( (x.strip().strip(".,;-:") for word in a for x in word.split() 
              if x.strip().strip(".,;-:").isalpha()))

已经在生成步骤中淘汰了非字母单词。

答案 1 :(得分:0)

Python有一个内置的.count方法,在这里非常有用:

lista = [ 
    'Fri, 19 Aug 2011 19:28:17 -0000', 
    'Fri, 19 Aug 2011 19:28:17 -0000', 
    'Sun, 19 Jan 2011 19:28:17 -0000', 
    'Sun, 19 Aug 2011 19:28:17 -0000', 
    'Fri, 19 Jan 2011 19:28:17 -0000', 
    'Mon, 05 Feb 2012 11:00:00 -0000',
    'Mon, 05 Nov 2012 11:00:00 -0000',
    'Wed, 05 Feb 2012 11:00:00 -0000',
    'Tue, 05 Nov 2012 11:00:00 -0000',
    'Tue, 05 Dec 2012 11:00:00 -0000',
    'Wed, 05 Jan 2012 11:00:00 -0000',
]

listb = (''.join(lista)).split()

for index, item in enumerate(listb):
    count = {}
    for item in listb:
        count[item] = listb.count(item)

months = ['Jan', 'Feb', 'Aug', 'Nov', 'Dec']

for k in count:
    if k in months:
        print(f"{k}: {count[k]}")

输出:

(xenial)vash@localhost:~/python/stack_overflow$ python3.7 count_months.py 
Aug: 3
Jan: 3
Feb: 2
Nov: 2
Dec: 1

会发生什么,我们将itemslista中的所有join合并为一个string。然后,我们split使用该字符串来获取所有单独的words。 现在我们可以使用count方法并创建一个dictionary来保存计数。我们可以创建一个list的{​​{1}},我们要从items中检索,而仅检索那些dicionary