我们比较了满足约束的列表中的计数元素(下面示例中的约束,如果元素是奇数的话)。
在python3中,len比sum快得多
$ python3 -m timeit -s 'X = list(range(1000))' 'len([1 for x in X if x % 2])'
5000 loops, best of 5: 41.4 usec per loop
$ python3 -m timeit -s 'X = list(range(1000))' 'sum(1 for x in X if x % 2)'
5000 loops,
有没有一种方法可以在Python2和Python3中高效地迭代字典中的值/项?
在Python 2中,我可以编写
for x in mydict:
for x in mydict.iterkeys():
for x in mydict.viewkeys():
for x in mydict.itervalues():
for x in mydict.viewvalues():
for x in mydict.iteritems():
for x in mydict.viewitems():
在Python 3中,我有以下可能性:
for x in mydict:
for x in mydict
我认为我很清楚在Python中变量和生成器是如何工作的。
然而,下面的代码让我感到困惑。
from __future__ import print_function
class A(object):
x = 4
gen = (x for _ in range(3))
a = A()
print(list(a.gen))
当运行代码(Python 2)时,它说:
追溯(最近一次调用):文件"Untitled 8.py",第10行,打印(列表(a.gen))文件"Untitled 8.py",第6行,in gen = (x for _ in r
我使用boost.python使Python可以使用两个C++类,
class X {
public:
X();
}
class Y {
...
}
BOOST_PYTHON_MODULE(test) {
class_<X>("X", init<>());
class_<Y>("Y", init<>());
}
每当我用Python创建一个新的X时,我都想在C++中运行一些代码,它创建一个Y类型的本地对象。
x = X()
在Python中,我想让它运行
y = Y()
也
我正在尝试使用RubyPython模块()从Ruby中执行Python。我的模块都设置正确,但我很困惑如何使用它。
如果我有一段Python代码作为文本,请说:
def multiply(x, y):
return x * y * y
z = multiply(x, y)
我如何将它传递给Python以在Ruby中动态定义'x‘和'y’来执行,然后能够检索'z‘的值?
到目前为止,按评论请求编辑,这是可行的,对我来说也是有意义的:
RubyPython.start(python_exe: "/usr/bin/python2.6")
cPickl
有了一些Ruby经验,我开始学习Python和映射列表转换技术(select/ map /reduce)到Python。假设我想取一个列表0..99,取偶数的平方并对其进行汇总。
在Python中:
arr = range(100)
res = [x*x for x in arr if x % 2 == 0]
res = reduce(lambda x,y: x+y, res)
在Ruby中
(0..99)
.select {|num| num % 2 == 0}
.map {|num| num*num}
.inject {|sum, n| sum + n}
到目前为止,在Pyth
执行以下示例代码以从列表中删除元素:
l = ['A', 'B', 'C', 'D']
for x in l:
print(x, l)
if x == 'A' or x == 'B':
l.remove(x)
print(l)
Python2.x和Python3.x的输出都是:
$ python3 test.py
我刚刚从那里了解到,列表理解也会将它们的循环变量“泄漏”到周围的作用域中。
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
>>> x = 'before'
>>> a = [x for x in (1, 2, 3)]
>>> x
3
这个bug是在Python3中修复的。
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
>>> x = 'before'
>>> a = [x for
我正在尝试运行一个比较测试,该测试需要对来自python脚本和R脚本的结果进行多次迭代。使用网格化程序包中的repl_python(),每件事都可以在一次迭代中运行;但是,如果我试图在循环中运行它来获取复制,它就不能工作。 关于如何让python代码块在R中的循环中工作的想法? ###################################################
x <- 0
#run this line by line 5 times, end up with x = 5
repl_python()
a =
我知道如何从shell脚本调用我的python脚本。请告诉我如何将Python的输出作为变量收集回shell脚本中?
例如,我有一个shell脚本,它从while循环中调用Python。根据Python输出的值,循环是继续还是退出。
my.sh
x=0
while [ $x -lt 1 ]
do
#Get a value for x from my.py
python ./my.py
done
my.py
if something: x=1
else: x=0
x
另外,我可以得到多个python输出吗?例如,收集x& y的值?
my2.py
if something: x,y=1,1
我最近发现了Python的-i参数,脚本完成后的。挺干净的!
$ cat test.py
#!python3 -i
x=5
print('The value of x is ' + str(x))
$ ./test.py
The value of x is 5
>>> print(str(x+1))
6
>>>
zsh: suspended ./test.py
但是,当我试图将此脚本复制到一个在完成时终止的版本时,它会失败:
$ cat test1.py
#!python3
x=5
print('The value of x