我是Python的新手,我有一个简单的问题,比如我有一个项目列表:
['apple','red','apple','red','red','pear']
Run Code Online (Sandbox Code Playgroud)
什么是将列表项添加到字典中的最简单方法,并计算项目在列表中出现的次数.
所以对于上面的列表,我希望输出为:
{'apple': 2, 'red': 3, 'pear': 1}
Run Code Online (Sandbox Code Playgroud) 我在另一个问题上看到,我可以使用它Counter()来计算一组字符串中出现的次数.所以如果['A','B','A','C','A','A']我得到了Counter({'A':3,'B':1,'C':1}).但是现在,我如何使用该信息来构建直方图?
问题是当我的数据集只包含整数时,我正在使用的方法给出了浮点数的频率.为什么会发生这种情况以及如何从数据中获取整数频率?
我正在使用pyplot.histogram来绘制出现频率的直方图
import numpy as np
import matplotlib.pyplot as plt
from numpy import *
data = loadtxt('data.txt',dtype=int,usecols=(4,)) #loading 5th column of csv file into array named data.
plt.hist(data) #plotting the column as histogram
Run Code Online (Sandbox Code Playgroud)
我得到直方图,但我注意到如果我"打印"hist(数据)
hist=np.histogram(data)
print hist(data)
Run Code Online (Sandbox Code Playgroud)
我明白了:
(array([ 2323, 16338, 1587, 212, 26, 14, 3, 2, 2, 2]),
array([ 1. , 2.8, 4.6, 6.4, 8.2, 10. , 11.8, 13.6, 15.4,
17.2, 19. ]))
Run Code Online (Sandbox Code Playgroud)
其中第二个数组表示值,第一个数组表示出现次数.
在我的数据集中,所有值都是整数,第二个数组如何发生浮动数字以及如何获得整数频率?
更新:
这解决了问题,谢谢Lev的回复.
plt.hist(data, bins=np.arange(data.min(), data.max()+1))
Run Code Online (Sandbox Code Playgroud)
为了避免创建一个新问题,我如何为每个整数绘制"中间"列?比如说,我希望整数3的列占用2.5到3.5之间的空间而不是3到4之间的空间.

我用timeit获得了非常令人惊讶的结果,有人可以告诉我,如果我做错了吗?我使用的是Python 2.7.
这是文件speedtest_init.py的内容:
import random
to_count = [random.randint(0, 100) for r in range(60)]
Run Code Online (Sandbox Code Playgroud)
这些是speedtest.py的内容:
__author__ = 'BlueTrin'
import timeit
def test_init1():
print(timeit.timeit('import speedtest_init'))
def test_counter1():
s = """\
d = defaultdict(int);
for i in speedtest_init.to_count:
d[i] += 1
"""
print(timeit.timeit(s, 'from collections import defaultdict; import speedtest_init;'))
def test_counter2():
print(timeit.timeit('d = Counter(speedtest_init.to_count);', 'from collections import Counter; import speedtest_init;'))
if __name__ == "__main__":
test_init1()
test_counter1()
test_counter2()
Run Code Online (Sandbox Code Playgroud)
控制台输出是:
C:\Python27\python.exe C:/Dev/codility/chlorum2014/speedtest.py
2.71501962931
65.7090444503
91.2953839048
Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)
我认为默认情况下timeit()运行代码的1000000倍,所以我需要将时间除以1000000,但令人惊讶的是Counter慢于defaultdict().
这是预期的吗?
编辑:
使用dict也比defaultdict(int)更快: …
在Python中,我有一个项目列表,如:
mylist = [a, a, a, a, b, b, b, d, d, d, c, c, e]
Run Code Online (Sandbox Code Playgroud)
我想输出如下内容:
a (4)
b (3)
d (3)
c (2)
e (1)
Run Code Online (Sandbox Code Playgroud)
如何输出列表中项目的计数和排行榜?我不太关心效率,只是任何方式工作:)
谢谢!
可能重复:
如何计算列表中元素的频率?
我希望计算列表中相同值的元素数量并返回一个dict:
> a = map(int,[x**0.5 for x in range(20)])
> a
> [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
> number_of_elements_by_value(a)
> {0:1, 1:3, 2:5, 3:7, 4:4}
Run Code Online (Sandbox Code Playgroud)
我想这是一种直方图?
我想生成大量文本中最不常见单词的有序列表,其中最常见的单词首先出现,并且值指示它在文本中出现的次数.
我从一些在线期刊文章中删除了文本,然后简单地分配和分割;
article_one = """ large body of text """.split()
=> ("large","body", "of", "text")
Run Code Online (Sandbox Code Playgroud)
看起来像正则表达式适合接下来的步骤,但是对编程不熟悉我不太精通 - 如果最好的答案包括正则表达式,有人能指出我除了pydoc之外的一个很好的正则表达式教程吗?
使用字典计算输入字符串中字母出现的频率。只应计算字母,而不是空格、数字或标点符号。大写字母应被视为与小写字母相同。例如,count_letters("This is a sentence.") 应该返回 {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
def count_letters(text):
result = {}
# Go through each letter in the text
for letter in text:
# Check if the letter needs to be counted or not
if letter not in result:
result[letter.lower()] = 1
# Add or increment the value in the dictionary
else:
result[letter.lower()] += 1
return result
print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, …Run Code Online (Sandbox Code Playgroud) 在Python列表中查找连续重复字符串的最有效方法是什么?
例如,假设我有列表
["a", "a", "b", "c", "b","b","b"].我想要一个类似的输出:["group of 2 a's found at index 0, group of 3 b's found at index 4'].
是否有内置功能来完成此任务?我找到了numpy.bincount,但这似乎只适用于数值.
在此先感谢您的帮助.
我经常发现自己使用dict来计算某些东西的出现次数,我想知道是否有一种方法可以在不使用异常的情况下更顺畅.
count_dict = {}
for file in files:
############
#parse file#
############
for line in lines:
tokens = line.split()
if "something" in tokens:
try:
count_dict[tokens[0]] += 1
except KeyError:
count_dict[tokens[0]] = 1
Run Code Online (Sandbox Code Playgroud) 如何在列表中找到重复值?总会有一个重复的值
例如:
numbers=[1,2,3,4,5,3]
Run Code Online (Sandbox Code Playgroud)
我需要得到值3
这是我尝试的,但它有时打印相同列表的值2次.
endLoop=False
for n1 in range(0,len(numbers)):
for n2 in range(1,len(numbers)):
if numbers[n1]==numbers[n2]:
print numbers
print numbers[n1]
endLoop=True
if endLoop:
break
Run Code Online (Sandbox Code Playgroud) 我见过这个和这个.我想知道我是否可以在不使用像集合这样的库的情况下完成它,但是使用简单的循环结构.我可以用Python做到这一点吗?
void printRepeating(int arr[], int size)
{
int *count = (int *)calloc(sizeof(int), (size - 2));
int i;
printf(" Repeating elements are ");
for(i = 0; i < size; i++)
{
if(count[arr[i]] == 1)
printf(" %d ", arr[i]);
else
count[arr[i]]++;
}
}
Run Code Online (Sandbox Code Playgroud)
我试过这样做 -
a=[1,2,3,2,4,3,1,7,4,3];
b=[];
for i in a:
b[i]=b[i]+1;
Run Code Online (Sandbox Code Playgroud)
但我明白了
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)
有办法解决吗?
python ×13
list ×4
counter ×2
histogram ×2
python-2.7 ×2
count ×1
defaultdict ×1
dictionary ×1
for-loop ×1
matplotlib ×1
timeit ×1