小编Bak*_*riu的帖子

如何使用pyplot.bar绘制正误差条?

我试图用正误差线和图中的最大值绘制4个平均值.

means   = [26.82,26.4,61.17,61.55]         # Mean Data 
stds    = [4.59,4.39,4.37,4.38]            # Standard deviation Data
peakval = ['26.82','26.4','61.17','61.55'] # String array of means

ind = np.arange(len(means))
width = 0.35
colours = ['red','blue','green','yellow']

pyplot.figure()
pyplot.title('Average Age')
for i in range(len(means)):
    pyplot.bar(ind[i],means[i],width,color=colours[i],align='center',yerr=stds[i],ecolor='k')
pyplot.ylabel('Age (years)')
pyplot.xticks(ind,('Young Male','Young Female','Elderly Male','Elderly Female'))

def autolabel(bars,peakval):
    for ii,bar in enumerate(bars):
        height = bars[ii]
        pyplot.text(ind[ii], height-5, '%s'% (peakval[ii]), ha='center', va='bottom')
autolabel(means,peakval)    
Run Code Online (Sandbox Code Playgroud)

但是我无法找出如何只绘制正误差条.所以我最终得到了这样一个图:

平均年龄

任何建议将不胜感激.

python matplotlib bar-chart

13
推荐指数
1
解决办法
8833
查看次数

如何定义作为函数的枚举值?

我有一种情况需要强制执行,并为用户提供多个select函数之一的选项,作为参数传递给另一个函数:

我真的想要实现以下内容:

from enum import Enum

#Trivial Function 1
def functionA():
    pass

#Trivial Function 2
def functionB():
    pass

#This is not allowed (as far as i can tell the values should be integers)
#But pseudocode for what I am after
class AvailableFunctions(Enum):
    OptionA = functionA
    OptionB = functionB
Run Code Online (Sandbox Code Playgroud)

所以可以执行以下操作:

def myUserFunction(theFunction = AvailableFunctions.OptionA):
   #Type Check
   assert isinstance(theFunction,AvailableFunctions) 

   #Execute the actual function held as value in the enum or equivalent
   return theFunction.value() 
Run Code Online (Sandbox Code Playgroud)

python enums function

13
推荐指数
3
解决办法
4810
查看次数

函数名的别名具有不同的类型签名.为什么?

import Data.List (genericLength)

len = genericLength

:t genericLength
genericLength :: (Num i) => [b] -> i
:t len
len :: [b] -> Integer
Run Code Online (Sandbox Code Playgroud)

为什么类型len不同genericLength?这里的目的是使用更短的别名genericLength.

haskell中的功能不是一流的吗?不应该为功能结果赋予相同功能的其他名称吗?

haskell types

12
推荐指数
1
解决办法
1232
查看次数

如果参数是一个集合,为什么union会消耗更多内存?

我对sets 的内存分配行为感到困惑:

>>> set(range(1000)).__sizeof__()
32968
>>> set(range(1000)).union(range(1000)).__sizeof__()       # expected, set doesn't change
32968
>>> set(range(1000)).union(list(range(1000))).__sizeof__() #expected, set doesn't change
32968
>>> set(range(1000)).union(set(range(1000))).__sizeof__()  # not expected
65736
Run Code Online (Sandbox Code Playgroud)

为什么使用setas参数会使结果使用的内存量翻倍set?两种情况下的结果与原始情况相同set:

>>> set(range(1000)) == set(range(1000)).union(range(1000)) == set(range(1000)).union(set(range(1000)))
True
Run Code Online (Sandbox Code Playgroud)

请注意,使用普通迭代器会发生同样的情况:

>>> set(range(1000)).union(iter(list(range(1000)))).__sizeof__()
32968
Run Code Online (Sandbox Code Playgroud)

并与update方法:

>>> a.update(range(1000))
>>> a.__sizeof__()
32968
>>> a.update(set(range(1000)))
>>> a.__sizeof__()
65736
Run Code Online (Sandbox Code Playgroud)

起初,我认为这是因为当union被调用时,它看到其他的尺寸set1000,因此决定将分配足够的内存,以适应双方的所有元素setS,但后来它仅使用内存的一部分,而在迭代器的情况下,它只是迭代它并逐个添加元素(由于所有元素已经存在,因此不会占用更多内存set).

range也是一个序列,list第一个例子也是如此.

>>> len(range(1000))
1000
>>> …
Run Code Online (Sandbox Code Playgroud)

python memory-management set

12
推荐指数
1
解决办法
218
查看次数

对于循环括号

public class MultithreadingFour {
        public static void main(String args[]){
                A obj = new A();
                Task task= new Task();
                for(int i=0; i<10; i++)
                        Thread t= obj.newThread(task);
        }
}
Run Code Online (Sandbox Code Playgroud)

编译错误:此行有多个标记

Syntax error, insert ";" to complete Statement
  t cannot be resolved to a variable
Syntax error, insert "AssignmentOperator Expression" to complete Assignment
Syntax error, insert ":: IdentifierOrNew" to complete ReferenceExpression
  Thread cannot be resolved to a variable
Run Code Online (Sandbox Code Playgroud)

public class MultithreadingFour {
        public static void main(String args[]){
                A obj = new A(); …
Run Code Online (Sandbox Code Playgroud)

java for-loop

12
推荐指数
2
解决办法
554
查看次数

如何并行化文件下载?

我可以一次下载一个文件:

import urllib.request

urls = ['foo.com/bar.gz', 'foobar.com/barfoo.gz', 'bar.com/foo.gz']

for u in urls:
  urllib.request.urlretrieve(u)
Run Code Online (Sandbox Code Playgroud)

我可以尝试subprocess这样:

import subprocess
import os

def parallelized_commandline(command, files, max_processes=2):
    processes = set()
    for name in files:
        processes.add(subprocess.Popen([command, name]))
        if len(processes) >= max_processes:
            os.wait()
            processes.difference_update(
                [p for p in processes if p.poll() is not None])

    #Check if all the child processes were closed
    for p in processes:
        if p.poll() is None:
            p.wait()

urls = ['http://www.statmt.org/wmt15/training-monolingual-nc-v10/news-commentary-v10.en.gz',
'http://www.statmt.org/wmt15/training-monolingual-nc-v10/news-commentary-v10.cs.gz', 
'http://www.statmt.org/wmt15/training-monolingual-nc-v10/news-commentary-v10.de.gz']

parallelized_commandline('wget', urls)
Run Code Online (Sandbox Code Playgroud)

有没有办法在urlretrieve不使用os.systemsubprocess欺骗的情况下进行并行化? …

python subprocess wget download python-3.x

12
推荐指数
1
解决办法
7557
查看次数

在列表中交叉字符串的快速方法

如果有这样的列表:

shops=['A','B','C','D']
Run Code Online (Sandbox Code Playgroud)

并且想要创建以下新列表(我将每个元素彼此交叉并创建一个字符串,其中第一部分在第二部分之前是字母数字):

['A-B', 'A-C', 'A-D']

['A-B', 'B-C', 'B-D']

['A-C', 'B-C', 'C-D']

['A-D', 'B-D', 'C-D']
Run Code Online (Sandbox Code Playgroud)

我有这样的事情:

for a in shops:
    cons = []
    for b in shops:
        if a!=b:
            con = [a,b]
            con = sorted(con, key=lambda x: float(x))
            cons.append(con[0]+'-'+con[1])
    print(cons)
Run Code Online (Sandbox Code Playgroud)

但是,这对于大型列表来说相当慢(例如1000,其中我有1000*999*0.5输出).我一直在寻找一种更有效的方法吗?

我可以使用if-else子句进行排序,例如

for a in shops:
    cons = []
    for b in shops:
        if a<b:
            cons.append(a+"-"+b)
        elif a>b:
            cons.append(b+"-"+a)
    print(cons)
Run Code Online (Sandbox Code Playgroud)

哪个,我还没有定时 - 但我认为主要的减速是双循环

python list concatenation

12
推荐指数
1
解决办法
618
查看次数

避免使用jquery多次选择相同的选项

我有两个表Table1和Table2.每个表都包含<select>标记和选项,它们的值相同.

现在我想检查每个表,有多个选项存在多次.如果是,则已选择警报选项.

我的代码是:

$('#table1 tr').each(function() {
    $(this).find('select').change(function() { //alert($(this).val())
        if ($('option[value=' + $(this).val() + ']:selected').length > 1) {
            alert('option is already selected');
            $(this).val($(this).find("option:first").val());
        }
    });
});

$('#table2 tr').each(function() {
    $(this).find('select').change(function() { //alert($(this).val())
        if ($('option[value=' + $(this).val() + ']:selected').length > 1) {
            alert('option is already selected');
            $(this).val($(this).find("option:first").val());
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

当在第一个表和第二个表中选择相同时,它将提醒已选择的选项.我的代码出了什么问题?

你可以在这里测试代码.

html javascript jquery

11
推荐指数
1
解决办法
2175
查看次数

在Clojure中,是否有类似Haskell的函数?

在Haskell,我们有Data.Function.on:

on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
(.*.) `on` f = \x y -> f x .*. f y
Run Code Online (Sandbox Code Playgroud)

在Clojure中,我希望能够定义一个例如anagram谓词,如下所示:

(defn anagram? [word other-word]
  (and (not= word other-word)
       ((on = sort) word other-word)))
Run Code Online (Sandbox Code Playgroud)

实施起来很简单:

(defn on [g f] (fn [x y] (g (f x) (f y))))
Run Code Online (Sandbox Code Playgroud)

但是,是否有任何内置函数可以实现相同的目标?我好像找不到一个.

haskell functional-programming clojure combinators

11
推荐指数
1
解决办法
608
查看次数

当它们应该是同一个东西时,为什么>> =比concatMap更快?

昨晚,我正在编写一些娱乐代码,并且在某些时候我更换了一个concatMap,>>=并且在我的代码中看到了大约10%的加速.

我的印象是对于>>=for 的定义[]是完全正确的concatMap,所以我有点困惑.

performance haskell list ghc

11
推荐指数
1
解决办法
140
查看次数