标签归档:python-2.7

为什么提早归还比其他要慢?

问题:为什么提早归还比其他要慢?

这是我几天前给出的答案的后续问题。编辑:该问题的OP似乎已经使用了我发布给他的代码来问同样的问题,但是我没有意识到。道歉。提供的答案是不同的!

我基本上观察到:

>>> def without_else(param=False):
...     if param:
...         return 1
...     return 0
>>> def with_else(param=False):
...     if param:
...         return 1
...     else:
...         return 0
>>> from timeit import Timer as T
>>> T(lambda : without_else()).repeat()
[0.3011460304260254, 0.2866089344024658, 0.2871549129486084]
>>> T(lambda : with_else()).repeat()
[0.27536892890930176, 0.2693932056427002, 0.27011704444885254]
>>> T(lambda : without_else(True)).repeat()
[0.3383951187133789, 0.32756996154785156, 0.3279120922088623]
>>> T(lambda : with_else(True)).repeat()
[0.3305950164794922, 0.32186388969421387, 0.3209099769592285]

…或者换句话说:else无论if是否触发条件,使子句更快。

我认为这与两者生成的不同字节码有关,但是有人能详细确认/解释吗?

编辑:似乎不是每个人都可以重现我的时间安排,所以我认为在我的系统上提供一些信息可能有用。我正在运行安装了默认python的Ubuntu 11.10 64位。python生成以下版本信息:

Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
[GCC 4.6.1] on linux2

以下是Python 2.7中反汇编的结果:

>>> dis.dis(without_else)
  2           0 LOAD_FAST                0 (param)
              3 POP_JUMP_IF_FALSE       10

  3           6 LOAD_CONST               1 (1)
              9 RETURN_VALUE        

  4     >>   10 LOAD_CONST               2 (0)
             13 RETURN_VALUE        
>>> dis.dis(with_else)
  2           0 LOAD_FAST                0 (param)
              3 POP_JUMP_IF_FALSE       10

  3           6 LOAD_CONST               1 (1)
              9 RETURN_VALUE        

  5     >>   10 LOAD_CONST               2 (0)
             13 RETURN_VALUE        
             14 LOAD_CONST               0 (None)
             17 RETURN_VALUE        

This is a follow-up question to an answer I gave a few days back. Edit: it seems that the OP of that question already used the code I posted to him to ask the same question, but I was unaware of it. Apologies. The answers provided are different though!

Substantially I observed that:

>>> def without_else(param=False):
...     if param:
...         return 1
...     return 0
>>> def with_else(param=False):
...     if param:
...         return 1
...     else:
...         return 0
>>> from timeit import Timer as T
>>> T(lambda : without_else()).repeat()
[0.3011460304260254, 0.2866089344024658, 0.2871549129486084]
>>> T(lambda : with_else()).repeat()
[0.27536892890930176, 0.2693932056427002, 0.27011704444885254]
>>> T(lambda : without_else(True)).repeat()
[0.3383951187133789, 0.32756996154785156, 0.3279120922088623]
>>> T(lambda : with_else(True)).repeat()
[0.3305950164794922, 0.32186388969421387, 0.3209099769592285]

…or in other words: having the else clause is faster regardless of the if condition being triggered or not.

I assume it has to do with different bytecode generated by the two, but is anybody able to confirm/explain in detail?

EDIT: Seems not everybody is able to reproduce my timings, so I thought it might be useful to give some info on my system. I’m running Ubuntu 11.10 64 bit with the default python installed. python generates the following version information:

Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
[GCC 4.6.1] on linux2

Here are the results of the disassembly in Python 2.7:

>>> dis.dis(without_else)
  2           0 LOAD_FAST                0 (param)
              3 POP_JUMP_IF_FALSE       10

  3           6 LOAD_CONST               1 (1)
              9 RETURN_VALUE        

  4     >>   10 LOAD_CONST               2 (0)
             13 RETURN_VALUE        
>>> dis.dis(with_else)
  2           0 LOAD_FAST                0 (param)
              3 POP_JUMP_IF_FALSE       10

  3           6 LOAD_CONST               1 (1)
              9 RETURN_VALUE        

  5     >>   10 LOAD_CONST               2 (0)
             13 RETURN_VALUE        
             14 LOAD_CONST               0 (None)
             17 RETURN_VALUE        

回答 0

这纯粹是猜测,我还没有找到一种简单的方法来检查它是否正确,但是我有一个理论适合您。

我尝试了您的代码并获得了相同的结果,但without_else()反复地比with_else()

>>> T(lambda : without_else()).repeat()
[0.42015745017874906, 0.3188967452567226, 0.31984281521812363]
>>> T(lambda : with_else()).repeat()
[0.36009842032996175, 0.28962249392031936, 0.2927151355828528]
>>> T(lambda : without_else(True)).repeat()
[0.31709728471076915, 0.3172671387005721, 0.3285821242644147]
>>> T(lambda : with_else(True)).repeat()
[0.30939889008243426, 0.3035132258429485, 0.3046679117038593]

考虑到字节码是相同的,唯一的区别是函数的名称。特别是时序测试会在全局名称上进行查找。尝试重命名without_else(),区别消失:

>>> def no_else(param=False):
    if param:
        return 1
    return 0

>>> T(lambda : no_else()).repeat()
[0.3359846013948413, 0.29025818923918223, 0.2921801513879245]
>>> T(lambda : no_else(True)).repeat()
[0.3810395594970828, 0.2969634408842694, 0.2960104566362247]

我的猜测是,这without_else与其他内容发生了哈希冲突,globals()因此全局名称查找稍微慢一些。

编辑:具有7个或8个键的字典可能具有32个插槽,因此在此基础上,without_else哈希与__builtins__

>>> [(k, hash(k) % 32) for k in globals().keys() ]
[('__builtins__', 8), ('with_else', 9), ('__package__', 15), ('without_else', 8), ('T', 21), ('__name__', 25), ('no_else', 28), ('__doc__', 29)]

要阐明哈希如何工作:

__builtins__ 散列为-1196389688,这减小了表大小(32)的模数,这意味着它存储在表的#8插槽中。

without_else哈希到505688136,将模32的值降低为8,因此发生冲突。要解决此问题,Python计算:

从…开始:

j = hash % 32
perturb = hash

重复此过程,直到找到可用的插槽:

j = (5*j) + 1 + perturb;
perturb >>= 5;
use j % 2**i as the next table index;

这使它可以用作下一个索引17。幸运的是,它是免费的,因此循环仅重复一次。哈希表的大小是2的幂,哈希表的大小也是2的幂2**ii是哈希值使用的位数j

对该表的每个探测都可以找到以下之一:

  • 插槽为空,在这种情况下,探测停止,并且我们知道该值不在表中。

  • 该广告位尚未使用,但已在过去使用过,在这种情况下,我们尝试使用如上计算的下一个值。

  • 插槽已满,但是存储在表中的完整哈希值与我们要查找的键的哈希值不同(在__builtins__vs 的情况下就是这样without_else)。

  • 插槽已满,并且恰好具有我们想要的哈希值,然后Python检查以查看键和我们正在查找的对象是否是同一对象(在这种情况下,这是因为可能会插入标识符的短字符串被插入了,所以相同的标识符使用完全相同的字符串)。

  • 最终,当插槽已满时,哈希值完全匹配,但是键不是同一对象,然后Python才会尝试比较它们是否相等。这相对较慢,但实际上不应该进行名称查找。

This is a pure guess, and I haven’t figured out an easy way to check whether it is right, but I have a theory for you.

I tried your code and get the same of results, without_else() is repeatedly slightly slower than with_else():

>>> T(lambda : without_else()).repeat()
[0.42015745017874906, 0.3188967452567226, 0.31984281521812363]
>>> T(lambda : with_else()).repeat()
[0.36009842032996175, 0.28962249392031936, 0.2927151355828528]
>>> T(lambda : without_else(True)).repeat()
[0.31709728471076915, 0.3172671387005721, 0.3285821242644147]
>>> T(lambda : with_else(True)).repeat()
[0.30939889008243426, 0.3035132258429485, 0.3046679117038593]

Considering that the bytecode is identical, the only difference is the name of the function. In particular the timing test does a lookup on the global name. Try renaming without_else() and the difference disappears:

>>> def no_else(param=False):
    if param:
        return 1
    return 0

>>> T(lambda : no_else()).repeat()
[0.3359846013948413, 0.29025818923918223, 0.2921801513879245]
>>> T(lambda : no_else(True)).repeat()
[0.3810395594970828, 0.2969634408842694, 0.2960104566362247]

My guess is that without_else has a hash collision with something else in globals() so the global name lookup is slightly slower.

Edit: A dictionary with 7 or 8 keys probably has 32 slots, so on that basis without_else has a hash collision with __builtins__:

>>> [(k, hash(k) % 32) for k in globals().keys() ]
[('__builtins__', 8), ('with_else', 9), ('__package__', 15), ('without_else', 8), ('T', 21), ('__name__', 25), ('no_else', 28), ('__doc__', 29)]

To clarify how the hashing works:

__builtins__ hashes to -1196389688 which reduced modulo the table size (32) means it is stored in the #8 slot of the table.

without_else hashes to 505688136 which reduced modulo 32 is 8 so there’s a collision. To resolve this Python calculates:

Starting with:

j = hash % 32
perturb = hash

Repeat this until we find a free slot:

j = (5*j) + 1 + perturb;
perturb >>= 5;
use j % 2**i as the next table index;

which gives it 17 to use as the next index. Fortunately that’s free so the loop only repeats once. The hash table size is a power of 2, so 2**i is the size of the hash table, i is the number of bits used from the hash value j.

Each probe into the table can find one of these:

  • The slot is empty, in that case the probing stops and we know the value is not in the table.

  • The slot is unused but was used in the past in which case we go try the next value calculated as above.

  • The slot is full but the full hash value stored in the table isn’t the same as the hash of the key we are looking for (that’s what happens in the case of __builtins__ vs without_else).

  • The slot is full and has exactly the hash value we want, then Python checks to see if the key and the object we are looking up are the same object (which in this case they will be because short strings that could be identifiers are interned so identical identifiers use the exact same string).

  • Finally when the slot is full, the hash matches exactly, but the keys are not the identical object, then and only then will Python try comparing them for equality. This is comparatively slow, but in the case of name lookups shouldn’t actually happen.


找不到满足需求张量流的版本

问题:找不到满足需求张量流的版本

我安装了最新版本的Python (3.6.4 64-bit)和最新版本的PyCharm (2017.3.3 64-bit)。然后我在PyCharm中安装了一些模块(Numpy,Pandas等),但是当我尝试安装Tensorflow时却没有安装,并且出现了错误消息:

找不到满足TensorFlow要求的版本(来自版本:)找不到与TensorFlow匹配的发行版。

然后我尝试从命令提示符下安装TensorFlow,并得到了相同的错误消息。但是,我确实成功安装了tflearn。

我还安装了Python 2.7,但又收到了相同的错误消息。我搜索了该错误,并尝试了一些建议给其他人的方法,但是没有任何效果(包括安装Flask)。

我该如何安装Tensorflow?谢谢。

I installed the latest version of Python (3.6.4 64-bit) and the latest version of PyCharm (2017.3.3 64-bit). Then I installed some modules in PyCharm (Numpy, Pandas, etc), but when I tried installing Tensorflow it didn’t install, and I got the error message:

Could not find a version that satisfies the requirement TensorFlow (from versions: ) No matching distribution found for TensorFlow.

Then I tried installing TensorFlow from the command prompt and I got the same error message. I did however successfully install tflearn.

I also installed Python 2.7, but I got the same error message again. I googled the error and tried some of the things which were suggested to other people, but nothing worked (this included installing Flask).

How can I install Tensorflow? Thanks.


回答 0

截至2018年8月13日的Tensorflow支持Python 3.6.x和仅64位版本。

As of October 2020:

  • Tensorflow only supports the 64-bit version of Python

  • Tensorflow only supports Python 3.5 to 3.8

So, if you’re using an out-of-range version of Python (older or newer) or a 32-bit version, then you’ll need to use a different version.


回答 1

安装Tensorflow有两个重要规则:

  • 您必须安装Python x64。它在32b上不起作用,并且给出与您相同的错误。

  • 支持最新版本的Python3 = 3.7。

例如,您可以安装Python3.6.2-64bit,它的工作原理类似于Charm。

更新资料

据说在评论中,它可以在x64版本的Python3.8中使用。

There are a few important rules to install Tensorflow:

  • You have to install Python x64. It doesn’t work on 32b and it gives the same error as yours.

  • It doesn’t support Python versions later than 3.8 and Python 3.8 requires TensorFlow 2.2 or later.

For example, you can install Python3.8.6-64bit and it works like a charm.


回答 2

我成功安装了 pip install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl

I installed it successfully by pip install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl


回答 3

如果您使用anaconda,则默认情况下会安装python 3.7,因此您必须将其降级为3.6:

康达安装python = 3.6

然后:

点安装tensorflow

它在Ubuntu中为我工作。

if you are using anaconda, python 3.7 is installed by default, so you have to downgrade it to 3.6:

conda install python=3.6

then:

pip install tensorflow

it worked for me in Ubuntu.


回答 4

我正在为Windows提供它

如果您使用的是python-3

  1. 使用以下命令将pip升级到最新版本 py -m pip install --upgrade pip
  2. 使用安装软件包 py -m pip install <package-name>

如果您使用的是python-2

  1. 使用以下命令将pip升级到最新版本 py -2 -m pip install --upgrade pip
  2. 使用安装软件包 py -2 -m pip install <package-name>

对我有用

I am giving it for Windows

If you are using python-3

  1. Upgrade pip to the latest version using py -m pip install --upgrade pip
  2. Install package using py -m pip install <package-name>

If you are using python-2

  1. Upgrade pip to the latest version using py -2 -m pip install --upgrade pip
  2. Install package using py -2 -m pip install <package-name>

It worked for me


回答 5

根据Tensorflow python 3.8文档页面(截至2019年12月4日),该版本不可用。您将必须降级到python 3.7

Tensorflow isn’t available for python 3.8 (as of Dec 4th 2019) according to their documentation page. You will have to downgrade to python 3.7.


回答 6

卸载Python然后重新安装解决了我的问题,并且我能够成功安装TensorFlow。

Uninstalling Python and then reinstalling solved my issue and I was able to successfully install TensorFlow.


回答 7

不支持Python版本卸载python

https://www.python.org/downloads/release/python-362/

您应该在安装页面中检查并使用确切的版本。 https://www.tensorflow.org/install/install_windows

python 3.6.2或python 3.5.2为我解决了这个问题

Python version is not supported Uninstall python

https://www.python.org/downloads/release/python-362/

You should check and use the exact version in install page. https://www.tensorflow.org/install/install_windows

python 3.6.2 or python 3.5.2 solved this issue for me


回答 8

Tensorflow 2.2.0支持Python3.8

首先,请确保安装Python 3.8 64bit。出于某种原因,官方网站默认为32位。使用python -VV(两个大写字母V,不是W)验证此内容。然后照常继续:

python -m pip install --upgrade pip
python -m pip install wheel  # not necessary
python -m pip install tensorflow

与往常一样,请确保已安装CUDA 10.1和CuDNN。

Tensorflow 2.2.0 supports Python3.8

First, make sure to install Python 3.8 64bit. For some reason, the official site defaults to 32bit. Verify this using python -VV (two capital V, not W). Then continue as usual:

python -m pip install --upgrade pip
python -m pip install wheel  # not necessary
python -m pip install tensorflow

As usual, make sure you have CUDA 10.1 and CuDNN installed.


回答 9

看起来问题出在Python 3.8。请改用Python 3.7。我已采取步骤解决此问题。

  • 使用conda创建了python 3.7环境
  • 列表项在环境中使用pip install rasa安装了rasa。

为我工作。

Looks like the problem is with Python 3.8. Use Python 3.7 instead. Steps I took to solve this.

  • Created a python 3.7 environment with conda
  • List item Installed rasa using pip install rasa within the environment.

Worked for me.


回答 10

我在ubunu 18.04上使用python 3.6.8,对我来说解决方案是只升级pip

pip install --upgrade pip
pip install tensorflow==2.1.0

I am using python 3.6.8, on ubunu 18.04, for me the solution was to just upgrade pip

pip install --upgrade pip
pip install tensorflow==2.1.0

回答 11

Tensorflow似乎需要特殊版本的工具和库。Pip仅负责python版本。

要以专业的方式处理此问题(意味着它为我和其他人节省了Tremendos的时间),您必须为每个这样的软件设置一个特殊的环境。

为此,conda是一种高级工具。

我使用以下命令安装了Tensorflow:

sudo apt安装python3

sudo update-alternatives –install / usr / bin / python python / usr / bin / python3 1

sudo apt安装python3-pip

须藤apt-get install curl

卷曲https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh > Miniconda3-latest-Linux-x86_64.sh

bash Miniconda3-最新-Linux-x86_64.sh

来源〜/ .bashrc

  • 安装自己的phyton等

纳米.bashrc

  • 也许在这里插入您的代理等。

conda创建–name your_name python = 3

conda激活your_name

conda安装-c conda-forge tensorflow

  • 检查一切顺利

python -c“将tensorflow导入为tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000,1000])))”“

PS:一些可能有助于conda搜索tensorflow的命令

https://www.tensorflow.org/install/pip

使用virtualenv。康达更胜任。迷你主义者就足够了;不需要完整的conda

Tensorflow seems to need special versions of tools and libs. Pip only takes care of python version.

To handle this in a professional way (means it save tremendos time for me and others) you have to set a special environment for each software like this.

An advanced tool for this is conda.

I installed Tensorflow with this commands:

sudo apt install python3

sudo update-alternatives –install /usr/bin/python python /usr/bin/python3 1

sudo apt install python3-pip

sudo apt-get install curl

curl https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh > Miniconda3-latest-Linux-x86_64.sh

bash Miniconda3-latest-Linux-x86_64.sh

yes

source ~/.bashrc

  • installs its own phyton etc

nano .bashrc

  • maybe insert here your proxies etc.

conda create –name your_name python=3

conda activate your_name

conda install -c conda-forge tensorflow

  • check everything went well

python -c “import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))”

PS: some commands that may be helpful conda search tensorflow

https://www.tensorflow.org/install/pip

uses virtualenv. Conda is more capable. Miniconda ist sufficient; the full conda is not necessary


回答 12

tensorflow安装为我解决之前运行此命令:

pip install "pip>=19"

正如tensorflow的系统要求所述:

点19.0或更高版本

Running this before the tensorflow installation solved it for me:

pip install "pip>=19"

As the tensorflow‘s system requirements states:

pip 19.0 or later


回答 13

使用python 3.6或3.7版本,但重要的是您应该安装python版本的64位。

use python version 3.6 or 3.7 but the important thing is you should install the python version of 64-bit.


回答 14

对于TensorFlow 2.2版本:

  1. 确保您拥有python 3.8

尝试: python --version

要么 python3 --version

要么 py --version

  1. 升级python版本3.8的pip

尝试: python3 -m pip install --upgrade pip

要么 python -m pip install --upgrade pip

要么 py -m pip install --upgrade pip

  1. 安装TensorFlow:

尝试: python3 -m pip install TensorFlow

要么 python -m pip install TensorFlow

要么 py -m pip install TensorFlow

  1. 确保使用正确的python运行文件:

尝试: python3 file.py

要么 python file.py

要么 py file.py

For version TensorFlow 2.2:

  1. Make sure you have python 3.8

try: python --version

or python3 --version

or py --version

  1. Upgrade the pip of the python which has version 3.8

try: python3 -m pip install --upgrade pip

or python -m pip install --upgrade pip

or py -m pip install --upgrade pip

  1. Install TensorFlow:

try: python3 -m pip install TensorFlow

or python -m pip install TensorFlow

or py -m pip install TensorFlow

  1. Make sure to run the file with the correct python:

try: python3 file.py

or python file.py

or py file.py


回答 15

通过一一安装所需的所有软件包,我解决了与python 3.7相同的问题

步骤如下:

  1. 安装套件
  2. 请参阅错误消息:

    找不到满足要求的版本-所需模块的名称

  3. 安装所需的模块。通常,安装所需的模块需要安装另一个模块,以及另一个模块-其他两个模块,依此类推。

这样,我安装了30多个软件包,并有所帮助。现在我有了python 3.7中最新版本的tensorflow,而不必降级内核。

I solved the same problem with python 3.7 by installing one by one all the packages required

Here are the steps:

  1. Install the package
  2. See the error message:

    couldn’t find a version that satisfies the requirement — the name of the module required

  3. Install the module required. Very often, installation of the required module requires the installation of another module, and another module – a couple of the others and so on.

This way I installed more than 30 packages and it helped. Now I have tensorflow of the latest version in Python 3.7 and didn’t have to downgrade the kernel.


在IPython Notebook中同时使用Python 2.x和Python 3.x

问题:在IPython Notebook中同时使用Python 2.x和Python 3.x

我使用IPython笔记本,并且希望能够选择在IPython中创建2.x或3.x python笔记本。

我最初有Anaconda。使用Anaconda时,必须更改全局环境变量以选择所需的python版本,然后才能启动IPython。这不是我想要的,所以我卸载了Anaconda,现在使用MacPorts和PiP设置了自己的安装。看来我还是要用

port select --set python <python version> 

在python 2.x和3.x之间切换。这并不比anaconda解决方案好。

启动IPython笔记本后,是否有一种方法可以选择要使用的python版本,最好使用当前的MacPorts构建?

I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.

I initially had Anaconda. With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started. This is not what I was looking for so I uninstalled Anaconda and now have set up my own installation using MacPorts and PiP. It seems that I still have to use

port select --set python <python version> 

to toggle between python 2.x and 3.x. which is no better than the anaconda solution.

Is there a way to select what version of python you want to use after you start an IPython notebook, preferably with my current MacPorts build?


回答 0

这里的想法是安装多个ipython内核。这是有关Python的说明。如果你不使用Python,我最近添加的说明采用纯virtualenvs。

水蟒> = 4.1.0

从版本4.1.0开始,anaconda包含一个特殊的程序包nb_conda_kernels,该程序包可检测笔记本内核的conda环境并自动注册它们。这使得使用新的python版本就像创建新的conda环境一样容易:

conda create -n py27 python=2.7 ipykernel
conda create -n py36 python=3.6 ipykernel

重新启动jupyter notebook之后,新内核可通过图形界面使用。请注意,必须将新软件包明确安装到新环境中。conda文档中的“ 管理环境”部分提供了更多信息。

手动注册内核

不想使用nb_conda_kernels或仍使用旧版本的anaconda的用户可以使用以下步骤来手动注册ipython内核。

配置python2.7环境:

conda create -n py27 python=2.7
conda activate py27
conda install notebook ipykernel
ipython kernel install --user

配置python3.6环境:

conda create -n py36 python=3.6
conda activate py36
conda install notebook ipykernel
ipython kernel install --user

在此之后,你应该能够之间进行选择python2
python3创造的接口一个新的笔记本时。

另外,如果要更改内核名称,可以将--name--display-name选项传递给ipython kernel install。请参阅ipython kernel install --help以获取更多信息。

The idea here is to install multiple ipython kernels. Here are instructions for anaconda. If you are not using anaconda, I recently added instructions using pure virtualenvs.

Anaconda >= 4.1.0

Since version 4.1.0, anaconda includes a special package nb_conda_kernels that detects conda environments with notebook kernels and automatically registers them. This makes using a new python version as easy as creating new conda environments:

conda create -n py27 python=2.7 ipykernel
conda create -n py36 python=3.6 ipykernel

After a restart of jupyter notebook, the new kernels are available over the graphical interface. Please note that new packages have to be explicitly installed into the new environments. The Managing environments section in conda’s docs provides further information.

Manually registering kernels

Users who do not want to use nb_conda_kernels or still use older versions of anaconda can use the following steps to manually register ipython kernels.

configure the python2.7 environment:

conda create -n py27 python=2.7
conda activate py27
conda install notebook ipykernel
ipython kernel install --user

configure the python3.6 environment:

conda create -n py36 python=3.6
conda activate py36
conda install notebook ipykernel
ipython kernel install --user

After that you should be able to choose between python2
and python3 when creating a new notebook in the interface.

Additionally you can pass the --name and --display-name options to ipython kernel install if you want to change the names of your kernels. See ipython kernel install --help for more informations.


回答 1

如果您在Python 3上运行Jupyter,则可以这样设置Python 2内核:

python2 -m pip install ipykernel

python2 -m ipykernel install --user

http://ipython.readthedocs.io/en/stable/install/kernel_install.html

If you’re running Jupyter on Python 3, you can set up a Python 2 kernel like this:

python2 -m pip install ipykernel

python2 -m ipykernel install --user

http://ipython.readthedocs.io/en/stable/install/kernel_install.html


回答 2

这些说明说明了如何为非anaconda用户在单独的虚拟环境中安装python2和python3内核。如果您使用anaconda,请找到我的其他答案,以直接针对anaconda量身定制解决方案。

我假设您已经jupyter notebook安装了。


首先,请确保您有python2和提供的python3口译员pip

在ubuntu上,您可以通过以下方式安装它们:

sudo apt-get install python-dev python3-dev python-pip python3-pip

接下来准备并注册内核环境

python -m pip install virtualenv --user

# configure python2 kernel
python -m virtualenv -p python2 ~/py2_kernel
source ~/py2_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py2 --user
deactivate

# configure python3 kernel
python -m virtualenv -p python3 ~/py3_kernel
source ~/py3_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py3 --user
deactivate

为了简化操作,您可能需要将激活命令的外壳别名添加到外壳配置文件中。根据不同的系统和外壳使用,这可以是例如~/.bashrc~/.bash_profile~/.zshrc

alias kernel2='source ~/py2_kernel/bin/activate'
alias kernel3='source ~/py3_kernel/bin/activate'

重新启动外壳程序后,现在可以在激活要使用的环境后安装新软件包。

kernel2
python -m pip install <pkg-name>
deactivate

要么

kernel3
python -m pip install <pkg-name>
deactivate

These instructions explain how to install a python2 and python3 kernel in separate virtual environments for non-anaconda users. If you are using anaconda, please find my other answer for a solution directly tailored to anaconda.

I assume that you already have jupyter notebook installed.


First make sure that you have a python2 and a python3 interpreter with pip available.

On ubuntu you would install these by:

sudo apt-get install python-dev python3-dev python-pip python3-pip

Next prepare and register the kernel environments

python -m pip install virtualenv --user

# configure python2 kernel
python -m virtualenv -p python2 ~/py2_kernel
source ~/py2_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py2 --user
deactivate

# configure python3 kernel
python -m virtualenv -p python3 ~/py3_kernel
source ~/py3_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py3 --user
deactivate

To make things easier, you may want to add shell aliases for the activation command to your shell config file. Depending on the system and shell you use, this can be e.g. ~/.bashrc, ~/.bash_profile or ~/.zshrc

alias kernel2='source ~/py2_kernel/bin/activate'
alias kernel3='source ~/py3_kernel/bin/activate'

After restarting your shell, you can now install new packages after activating the environment you want to use.

kernel2
python -m pip install <pkg-name>
deactivate

or

kernel3
python -m pip install <pkg-name>
deactivate

回答 3

使用当前版本的Notebook / Jupyter,您可以创建Python3内核。使用Python 2从命令行启动新的笔记本应用程序后,您应该在下拉菜单“新建”中看到条目“ Python 3”。这为您提供了一个使用Python 3的笔记本。因此,您可以并排放置两个笔记本,并使用不同的Python版本。

细节

  1. 创建此目录: mkdir -p ~/.ipython/kernels/python3
  2. ~/.ipython/kernels/python3/kernel.json使用以下内容创建此文件:

    {
        "display_name": "IPython (Python 3)", 
        "language": "python", 
        "argv": [
            "python3", 
            "-c", "from IPython.kernel.zmq.kernelapp import main; main()", 
            "-f", "{connection_file}"
        ], 
        "codemirror_mode": {
            "version": 2, 
            "name": "ipython"
        }
    }
  3. 重新启动笔记本服务器。

  4. 从下拉菜单“新建”中选择“ Python 3”
  5. 使用Python 3笔记本
  6. 从下拉菜单“新建”中选择“ Python 2”
  7. 使用Python 2笔记本

With a current version of the Notebook/Jupyter, you can create a Python3 kernel. After starting a new notebook application from the command line with Python 2 you should see an entry „Python 3“ in the dropdown menu „New“. This gives you a notebook that uses Python 3. So you can have two notebooks side-by-side with different Python versions.

The Details

  1. Create this directory: mkdir -p ~/.ipython/kernels/python3
  2. Create this file ~/.ipython/kernels/python3/kernel.json with this content:

    {
        "display_name": "IPython (Python 3)", 
        "language": "python", 
        "argv": [
            "python3", 
            "-c", "from IPython.kernel.zmq.kernelapp import main; main()", 
            "-f", "{connection_file}"
        ], 
        "codemirror_mode": {
            "version": 2, 
            "name": "ipython"
        }
    }
    
  3. Restart the notebook server.

  4. Select „Python 3“ from the dropdown menu „New“
  5. Work with a Python 3 Notebook
  6. Select „Python 2“ from the dropdown menu „New“
  7. Work with a Python 2 Notebook

回答 4

提供了一个解决方案,该解决方案允许我通过配置Ipython kernelspec来保留MacPorts的安装。

要求:

  • MacPorts安装在通常的/ opt目录中
  • python 2.7是通过macports安装的
  • python 3.4通过macports安装
  • 为python 2.7安装了ipython
  • 为python 3.4安装了ipython

对于python 2.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin
$ sudo ./ipython kernelspec install-self

对于python 3.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin
$ sudo ./ipython kernelspec install-self

现在,您可以打开一个Ipython笔记本,然后选择python 2.x或python 3.x笔记本。

A solution is available that allows me to keep my MacPorts installation by configuring the Ipython kernelspec.

Requirements:

  • MacPorts is installed in the usual /opt directory
  • python 2.7 is installed through macports
  • python 3.4 is installed through macports
  • Ipython is installed for python 2.7
  • Ipython is installed for python 3.4

For python 2.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin
$ sudo ./ipython kernelspec install-self

For python 3.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin
$ sudo ./ipython kernelspec install-self

Now you can open an Ipython notebook and then choose a python 2.x or a python 3.x notebook.


回答 5

通过我的Linux安装,我做到了:

sudo ipython2 kernelspec install-self

现在,我的python 2又回到了列表中。

参考:

http://ipython.readthedocs.org/en/latest/install/kernel_install.html


更新:

上面的方法现已弃用,将来会被删除。新方法应为:

sudo ipython2 kernel install

From my Linux installation I did:

sudo ipython2 kernelspec install-self

And now my python 2 is back on the list.

Reference:

http://ipython.readthedocs.org/en/latest/install/kernel_install.html


UPDATE:

The method above is now deprecated and will be dropped in the future. The new method should be:

sudo ipython2 kernel install


回答 6

以下是将python2内核添加到jupyter笔记本的步骤:

打开一个终端并创建一个新的python 2环境: conda create -n py27 python=2.7

激活环境:Linux source activate py27或Windowsactivate py27

在环境中安装内核: conda install notebook ipykernel

在env外部安装内核: ipython kernel install --user

关闭环境: source deactivate

尽管答案很晚,希望有人发现它有用:p

Following are the steps to add the python2 kernel to jupyter notebook::

open a terminal and create a new python 2 environment: conda create -n py27 python=2.7

activate the environment: Linux source activate py27 or windows activate py27

install the kernel in the env: conda install notebook ipykernel

install the kernel for outside the env: ipython kernel install --user

close the env: source deactivate

Although a late answer hope someone finds it useful :p


回答 7

使用sudo pip3 install jupyter安装了python3 jupyter和sudo pip install jupyter安装jupyter笔记本python2。然后,您可以调用ipython kernel install命令来启用两种类型的笔记本以在jupyter笔记本中进行选择。

Use sudo pip3 install jupyter for installing jupyter for python3 and sudo pip install jupyter for installing jupyter notebook for python2. Then, you can call ipython kernel install command to enable both types of notebook to choose from in jupyter notebook.


回答 8

我查看了这个出色的信息,然后想知道

  1. 我已经安装了python2,python3和IPython,
  2. 我安装了PyCharm,
  3. PyCharm将IPython用于其Python控制台,

如果 PyCharm将使用

  1. IPython的-PY2时菜单>文件>设置>项目>项目解释== PY2
  2. 当菜单>文件>设置>项目>项目解释器== py3时,IPython-py3

答案:是的!

PS我也安装了适用于Windows的Python启动器。

I looked at this excellent info and then wondered, since

  1. i have python2, python3 and IPython all installed,
  2. i have PyCharm installed,
  3. PyCharm uses IPython for its Python Console,

if PyCharm would use

  1. IPython-py2 when Menu>File>Settings>Project>Project Interpreter == py2 AND
  2. IPython-py3 when Menu>File>Settings>Project>Project Interpreter == py3

ANSWER: Yes!

P.S. i have Python Launcher for Windows installed as well.


回答 9

在Windows 7下,我安装了anaconda和anaconda3。我走进去\Users\me\anaconda\Scripts执行

sudo .\ipython kernelspec install-self

然后我走进去\Users\me\anaconda3\Scripts执行

sudo .\ipython kernel install

(我知道了 jupyter kernelspec install-self is DEPRECATED as of 4.0. You probably want 'ipython kernel install' to install the IPython kernelspec.

启动后jupyter notebook(在anaconda3中),我在右上角的“新建”下获得了一个整洁的下拉菜单,让我在Python 2 odr和Python 3内核之间进行选择。

Under Windows 7 I had anaconda and anaconda3 installed. I went into \Users\me\anaconda\Scripts and executed

sudo .\ipython kernelspec install-self

then I went into \Users\me\anaconda3\Scripts and executed

sudo .\ipython kernel install

(I got jupyter kernelspec install-self is DEPRECATED as of 4.0. You probably want 'ipython kernel install' to install the IPython kernelspec.)

After starting jupyter notebook (in anaconda3) I got a neat dropdown menu in the upper right corner under “New” letting me choose between Python 2 odr Python 3 kernels.


回答 10

  • 如果您在虚拟环境中运行anaconda。
  • 当您创建一个新笔记本时,我没有显示选择虚拟环境内核。
  • 然后,您必须使用以下命令将其设置到ipykernel中
$ pip install --user ipykernel
$ python -m ipykernel install --user --name=test2
  • If you are running anaconda in virtual environment.
  • And when you create a new notebook but i’s not showing to select the virtual environment kernel.
  • Then you have to set it into the ipykernel using the following command
$ pip install --user ipykernel
$ python -m ipykernel install --user --name=test2

如何按两列或更多列对python pandas中的dataFrame进行排序?

问题:如何按两列或更多列对python pandas中的dataFrame进行排序?

假设我有一个数据列a,其中包含,bc,我想b按升序按列对数据帧进行排序,然后按c降序按列对数据帧进行排序,我该怎么做?

Suppose I have a dataframe with columns a, b and c, I want to sort the dataframe by column b in ascending order, and by column c in descending order, how do I do this?


回答 0

从0.17.0版本开始,sort不推荐使用该方法,而推荐使用sort_valuessort在0.20.0版本中被完全删除。参数(和结果)保持不变:

df.sort_values(['a', 'b'], ascending=[True, False])

您可以使用的升序参数sort

df.sort(['a', 'b'], ascending=[True, False])

例如:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1

正如@renadeen所评论

默认情况下,排序不正确!因此,您应该将sort方法的结果分配给变量,或者将inplace = True添加到方法调用中。

也就是说,如果您想将df1用作已排序的DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

要么

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

As of the 0.17.0 release, the sort method was deprecated in favor of sort_values. sort was completely removed in the 0.20.0 release. The arguments (and results) remain the same:

df.sort_values(['a', 'b'], ascending=[True, False])

You can use the ascending argument of sort:

df.sort(['a', 'b'], ascending=[True, False])

For example:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1

As commented by @renadeen

Sort isn’t in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.

that is, if you want to reuse df1 as a sorted DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

or

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

回答 1

从熊猫0.17.0开始,DataFrame.sort()已弃用该熊猫,并将其设置为在以后的熊猫版本中将其删除。现在,按值对数据框进行排序的方法是DataFrame.sort_values

因此,您问题的答案现在是

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

As of pandas 0.17.0, DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

As such, the answer to your question would now be

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

回答 2

对于数字数据的大型数据框,您可能会通过看到显着的性能改进numpy.lexsort,该方法使用一系列键执行间接排序:

import pandas as pd
import numpy as np

np.random.seed(0)

df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
df1 = pd.concat([df1]*100000)

def pdsort(df1):
    return df1.sort_values(['a', 'b'], ascending=[True, False])

def lex(df1):
    arr = df1.values
    return pd.DataFrame(arr[np.lexsort((-arr[:, 1], arr[:, 0]))])

assert (pdsort(df1).values == lex(df1).values).all()

%timeit pdsort(df1)  # 193 ms per loop
%timeit lex(df1)     # 143 ms per loop

一个特殊之处是定义的排序顺序numpy.lexsort颠倒了:首先(-'b', 'a')按系列排序a。我们否定级数b以反映我们希望该级数降序排列。

请注意,np.lexsort仅使用数字值排序,而同时pd.DataFrame.sort_values使用字符串或数字值。np.lexsort与字符串一起使用将给出:TypeError: bad operand type for unary -: 'str'

For large dataframes of numeric data, you may see a significant performance improvement via numpy.lexsort, which performs an indirect sort using a sequence of keys:

import pandas as pd
import numpy as np

np.random.seed(0)

df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
df1 = pd.concat([df1]*100000)

def pdsort(df1):
    return df1.sort_values(['a', 'b'], ascending=[True, False])

def lex(df1):
    arr = df1.values
    return pd.DataFrame(arr[np.lexsort((-arr[:, 1], arr[:, 0]))])

assert (pdsort(df1).values == lex(df1).values).all()

%timeit pdsort(df1)  # 193 ms per loop
%timeit lex(df1)     # 143 ms per loop

One peculiarity is that the defined sorting order with numpy.lexsort is reversed: (-'b', 'a') sorts by series a first. We negate series b to reflect we want this series in descending order.

Be aware that np.lexsort only sorts with numeric values, while pd.DataFrame.sort_values works with either string or numeric values. Using np.lexsort with strings will give: TypeError: bad operand type for unary -: 'str'.


Python中%的结果是什么?

问题:Python中%的结果是什么?

什么是%在计算?我似乎无法弄清楚它的作用。

例如,它算出计算的百分比4 % 2吗:显然等于0。如何?

What does the % in a calculation? I can’t seem to work out what it does.

Does it work out a percent of the calculation for example: 4 % 2 is apparently equal to 0. How?


回答 0

%(模)运算符从第一个参数除以第二个参数得出余数。首先将数字参数转换为通用类型。零权限参数引发ZeroDivisionError异常。参数可以是浮点数,例如3.14%0.7等于0.34(因为3.14等于4 * 0.7 + 0.34。)模运算符始终产生与第二个操作数具有相同符号的结果(或为零);结果的绝对值严格小于第二个操作数的绝对值[2]。

取自http://docs.python.org/reference/expressions.html

例1: 6%2计算结果为0,如果将6除以2(3次),则没有余数。

实施例27%2评估为1因为有一个的其余部分1时7由2(3次)划分。

综上所述,它返回除法运算的余数,或者0没有余数。因此,6%2意味着找到6的余数除以2。

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

Taken from http://docs.python.org/reference/expressions.html

Example 1: 6%2 evaluates to 0 because there’s no remainder if 6 is divided by 2 ( 3 times ).

Example 2: 7%2 evaluates to 1 because there’s a remainder of 1 when 7 is divided by 2 ( 3 times ).

So to summarise that, it returns the remainder of a division operation, or 0 if there is no remainder. So 6%2 means find the remainder of 6 divided by 2.


回答 1

在某种程度上,主题%还用于字符串格式化操作,例如%=将值替换为字符串:

>>> x = 'abc_%(key)s_'
>>> x %= {'key':'value'}
>>> x 
'abc_value_'

同样,偏离主题,但它似乎是一个小记录功能,它花了一段时间来跟踪,并且我认为这是有关Python的模数计算的此SO页面高度行列。

Somewhat off topic, the % is also used in string formatting operations like %= to substitute values into a string:

>>> x = 'abc_%(key)s_'
>>> x %= {'key':'value'}
>>> x 
'abc_value_'

Again, off topic, but it seems to be a little documented feature which took me awhile to track down, and I thought it was related to Pythons modulo calculation for which this SO page ranks highly.


回答 2

像这样的表达式x % y求余数x ÷ y-从技术上讲,它是“模数”而不是“提醒”,因此,如果与其他语言%(余数运算符)进行比较,结果可能会有所不同。有一些细微的差异(如果您对实际的结果感兴趣,另请参见“为什么要使用Python的整数分区”)。

优先级与运算符/(除法)和*(乘法)相同。

>>> 9 / 2
4
>>> 9 % 2
1
  • 9除以2等于4。
  • 4乘2是8
  • 9减去8为1-余数。

Python陷阱:取决于您使用的Python版本,%它也是(不建议使用的)字符串插值运算符,因此请注意您是否来自使用自动类型转换的语言(如PHP或JS),在其中使用'12' % 2 + 3合法的表达式: Python,TypeError: not all arguments converted during string formatting这可能会使您感到困惑。

[Python 3更新]

用户n00p评论:

9/2在Python中为4.5。您必须像这样进行整数除法:9 // 2如果要python告诉您除法(4)之后还剩下多少个整个对象。

确切地说,整数除法曾经是Python 2中的默认设置(请注意,这个答案比我的男孩年龄大,这个男孩已经在学校学习,当时2.x是主流):

$ python2.7
Python 2.7.10 (default, Oct  6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4
>>> 9 // 2
4
>>> 9 % 2
1

在现代Python中,9 / 2结果4.5确实是:

$ python3.6
Python 3.6.1 (default, Apr 27 2017, 00:15:59)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4.5
>>> 9 // 2
4
>>> 9 % 2
1

[更新]

用户dahiya_boy在评论会话中询问:

问:能否请您解释原因-11 % 5 = 4-dahiya_boy

这很奇怪吧?如果您使用JavaScript尝试此操作:

> -11 % 5
-1

这是因为在JavaScript %中,它是“余数”运算符,而在Python中,它是“模数”(时钟数学)运算符。

您可以直接从GvR获得解释


编辑-dahiya_boy

在Java和iOS中,-11 % 5 = -1而在python和ruby中-11 % 5 = 4

Paulo Scardine解释了一半的原因,下面是其余的解释

在Java和iOS,%使剩余这意味着,如果你把11%的5 给出了Quotient = 2 and remainder = 1-11%5给出Quotient = -2 and remainder = -1

快速iOS中的示例代码。

但是当我们在python中谈论它时,它给出了时钟模数。及其使用以下公式的工作

mod(a,n) = a - {n * Floor(a/n)}

那就意味着

mod(11,5) = 11 - {5 * Floor(11/5)} => 11 - {5 * 2}

所以, mod(11,5) = 1

mod(-11,5) = -11 - 5 * Floor(11/5) => -11 - {5 * (-3)}

所以, mod(-11,5) = 4

python 3.0中的示例代码。


为什么Python的整数分区

今天(再次)被要求解释为什么Python中的整数除法返回结果的底数,而不是像C一样向零截断。

对于正数,不足为奇:

>>> 5//2
2

但是,如果其中一个操作数是负数,则结果是下限的,即从零舍入(朝负无穷大):

>>> -5//2
-3
>>> 5//-2
-3

这打扰了一些人,但是有一个很好的数学理由。整数除法运算(//)及其兄弟运算,取模运算(%)在一起并满足良好的数学关系(所有变量均为整数):

a/b = q with remainder r

这样

b*q + r = a and 0 <= r < b

(假设a和b> = 0)。

如果要使关系扩展为负a(使b为正),则有两种选择:如果将q截断为零,则r将变为负,因此不变量变为0 <= abs(r)<否则,您可以将q朝负无穷大移动,并且不变保持0 <= r <b。[更新:解决了此问题]

在数学数论中,数学家总是喜欢后一种选择(例如参见Wikipedia)。对于Python,我做出了相同的选择,因为模运算有一些有趣的应用,其中a的符号没有意义。考虑采用POSIX时间戳(自1970年初以来的秒数),并将其转换为一天中的时间。由于一天中有24 * 3600 = 86400秒,因此该计算仅为t%86400。但是,如果我们使用负数来表示1970年之前的时间,则“截断为零”规则将得出毫无意义的结果!使用下限规则,一切正常。

我想到的其他应用程序是计算机图形学中像素位置的计算。我敢肯定还有更多。

顺便说一下,对于负数b,所有事物都翻转了,并且不变式变为:

0 >= r > b.

那么C为什么不这样做呢?在设计C时,硬件可能没有这样做。而且硬件可能不会这样做,因为在最旧的硬件中,负数表示为“符号+幅度”,而不是如今使用的二进制补码表示法(至少对于整数)。我的第一台计算机是Control Data大型机,它使用整数和浮点数的补码。60的模式表示负零!

蒂姆·彼得斯(Tim Peters)知道所有Python的浮点骨架都埋在哪里,对我希望将这些规则扩展到浮点模数表示担忧。他可能是对的。当x是非常小的负数时,truncate-towards-negative-infinity规则会导致x%1.0的精度损失。但这还不足以打破整数模,并且//与之紧密耦合。

PS。请注意,我使用的是//而不是/-这是Python 3语法,并且在Python 2中也允许强调您知道自己正在调用整数除法。Python 2中的/运算符是模棱两可的,因为它对两个整数操作数返回的结果与对int和一个或两个或多个浮点数的返回不同。但这是一个完全独立的故事。参见PEP 238。

由Guido van Rossum发表于9:49 AM

An expression like x % y evaluates to the remainder of x ÷ y – well, technically it is “modulus” instead of “reminder” so results may be different if you are comparing with other languages where % is the remainder operator. There are some subtle differences (if you are interested in the practical consequences see also “Why Python’s Integer Division Floors” bellow).

Precedence is the same as operators / (division) and * (multiplication).

>>> 9 / 2
4
>>> 9 % 2
1
  • 9 divided by 2 is equal to 4.
  • 4 times 2 is 8
  • 9 minus 8 is 1 – the remainder.

Python gotcha: depending on the Python version you are using, % is also the (deprecated) string interpolation operator, so watch out if you are coming from a language with automatic type casting (like PHP or JS) where an expression like '12' % 2 + 3 is legal: in Python it will result in TypeError: not all arguments converted during string formatting which probably will be pretty confusing for you.

[update for Python 3]

User n00p comments:

9/2 is 4.5 in python. You have to do integer division like so: 9//2 if you want python to tell you how many whole objects is left after division(4).

To be precise, integer division used to be the default in Python 2 (mind you, this answer is older than my boy who is already in school and at the time 2.x were mainstream):

$ python2.7
Python 2.7.10 (default, Oct  6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4
>>> 9 // 2
4
>>> 9 % 2
1

In modern Python 9 / 2 results 4.5 indeed:

$ python3.6
Python 3.6.1 (default, Apr 27 2017, 00:15:59)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9 / 2
4.5
>>> 9 // 2
4
>>> 9 % 2
1

[update]

User dahiya_boy asked in the comment session:

Q. Can you please explain why -11 % 5 = 4 – dahiya_boy

This is weird, right? If you try this in JavaScript:

> -11 % 5
-1

This is because in JavaScript % is the “remainder” operator while in Python it is the “modulus” (clock math) operator.

You can get the explanation directly from GvR:


Edit – dahiya_boy

In Java and iOS -11 % 5 = -1 whereas in python and ruby -11 % 5 = 4.

Well half of the reason is explained by the Paulo Scardine, and rest of the explanation is below here

In Java and iOS, % gives the remainder that means if you divide 11 % 5 gives Quotient = 2 and remainder = 1 and -11 % 5 gives Quotient = -2 and remainder = -1.

Sample code in swift iOS.

But when we talk about in python its gives clock modulus. And its work with below formula

mod(a,n) = a - {n * Floor(a/n)}

Thats means,

mod(11,5) = 11 - {5 * Floor(11/5)} => 11 - {5 * 2}

So, mod(11,5) = 1

And

mod(-11,5) = -11 - 5 * Floor(-11/5) => -11 - {5 * (-3)}

So, mod(-11,5) = 4

Sample code in python 3.0.


Why Python’s Integer Division Floors

I was asked (again) today to explain why integer division in Python returns the floor of the result instead of truncating towards zero like C.

For positive numbers, there’s no surprise:

>>> 5//2
2

But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):

>>> -5//2
-3
>>> 5//-2
-3

This disturbs some people, but there is a good mathematical reason. The integer division operation (//) and its sibling, the modulo operation (%), go together and satisfy a nice mathematical relationship (all variables are integers):

a/b = q with remainder r

such that

b*q + r = a and 0 <= r < b

(assuming a and b are >= 0).

If you want the relationship to extend for negative a (keeping b positive), you have two choices: if you truncate q towards zero, r will become negative, so that the invariant changes to 0 <= abs(r) < otherwise, you can floor q towards negative infinity, and the invariant remains 0 <= r < b. [update: fixed this para]

In mathematical number theory, mathematicians always prefer the latter choice (see e.g. Wikipedia). For Python, I made the same choice because there are some interesting applications of the modulo operation where the sign of a is uninteresting. Consider taking a POSIX timestamp (seconds since the start of 1970) and turning it into the time of day. Since there are 24*3600 = 86400 seconds in a day, this calculation is simply t % 86400. But if we were to express times before 1970 using negative numbers, the “truncate towards zero” rule would give a meaningless result! Using the floor rule it all works out fine.

Other applications I’ve thought of are computations of pixel positions in computer graphics. I’m sure there are more.

For negative b, by the way, everything just flips, and the invariant becomes:

0 >= r > b.

So why doesn’t C do it this way? Probably the hardware didn’t do this at the time C was designed. And the hardware probably didn’t do it this way because in the oldest hardware, negative numbers were represented as “sign + magnitude” rather than the two’s complement representation used these days (at least for integers). My first computer was a Control Data mainframe and it used one’s complement for integers as well as floats. A pattern of 60 ones meant negative zero!

Tim Peters, who knows where all Python’s floating point skeletons are buried, has expressed some worry about my desire to extend these rules to floating point modulo. He’s probably right; the truncate-towards-negative-infinity rule can cause precision loss for x%1.0 when x is a very small negative number. But that’s not enough for me to break integer modulo, and // is tightly coupled to that.

PS. Note that I am using // instead of / — this is Python 3 syntax, and also allowed in Python 2 to emphasize that you know you are invoking integer division. The / operator in Python 2 is ambiguous, since it returns a different result for two integer operands than for an int and a float or two floats. But that’s a totally separate story; see PEP 238.

Posted by Guido van Rossum at 9:49 AM


回答 3

模数是一种数学运算,有时也称为“时钟算术”。我发现将其简单描述为剩余部分会产生误导和混乱,因为它掩盖了它在计算机科学中被大量使用的真正原因。它实际上是用于环绕循环的。

想想时钟:假设您以“军事”时间查看时钟,该时间范围为0:00-23.59。现在,如果您希望每天午夜发生一些事情,那么您希望当前时间mod 24为零:

如果(小时%24 == 0):

您可以想到历史中的所有小时都围绕24小时一圈地循环,并且一天中的当前小时是无限长的mod24。这是一个比余数更深刻的概念,这是一种数学方法处理周期,这在计算机科学中非常重要。它也用于环绕数组,允许您增加索引并使用模数在到达数组末尾后返回到开头。

The modulus is a mathematical operation, sometimes described as “clock arithmetic.” I find that describing it as simply a remainder is misleading and confusing because it masks the real reason it is used so much in computer science. It really is used to wrap around cycles.

Think of a clock: Suppose you look at a clock in “military” time, where the range of times goes from 0:00 – 23.59. Now if you wanted something to happen every day at midnight, you would want the current time mod 24 to be zero:

if (hour % 24 == 0):

You can think of all hours in history wrapping around a circle of 24 hours over and over and the current hour of the day is that infinitely long number mod 24. It is a much more profound concept than just a remainder, it is a mathematical way to deal with cycles and it is very important in computer science. It is also used to wrap around arrays, allowing you to increase the index and use the modulus to wrap back to the beginning after you reach the end of the array.


回答 4

Python-基本运算符
http://www.tutorialspoint.com/python/python_basic_operators.htm

模量-将左操作数除以右操作数并返回余数

a = 10和b = 20

b%a = 0

Python – Basic Operators
http://www.tutorialspoint.com/python/python_basic_operators.htm

Modulus – Divides left hand operand by right hand operand and returns remainder

a = 10 and b = 20

b % a = 0


回答 5

在大多数语言中,%用于模数。Python也不exceptions。

In most languages % is used for modulus. Python is no exception.


回答 6

%Modulo运算符也可以用于打印字符串(就像在C中一样),如Google https://developers.google.com/edu/python/strings上定义的那样。

      # % operator
  text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')

这似乎有点题外话,但肯定会有所帮助。

% Modulo operator can be also used for printing strings (Just like in C) as defined on Google https://developers.google.com/edu/python/strings.

      # % operator
  text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')

This seems to bit off topic but It will certainly help someone.


回答 7

x % y计算除法的余数x除以y其中的商是一个整数。其余的符号为y


在Python 3上计算得出6.75; 这是因为这样/做是真正的除法,而不是Python 2上的整数除法(默认情况下)(默认情况下)。在Python 2上1 / 4,由于结果舍入为0。

整数除法也可以在Python 3上使用//运算符完成,因此要得到7,可以执行:

3 + 2 + 1 - 5 + 4 % 2 - 1 // 4 + 6

此外,只需添加以下行,即可在Python 2上获得Python样式划分

from __future__ import division

作为每个源文件中的第一条源代码行。

x % y calculates the remainder of the division x divided by y where the quotient is an integer. The remainder has the sign of y.


On Python 3 the calculation yields 6.75; this is because the / does a true division, not integer division like (by default) on Python 2. On Python 2 1 / 4 gives 0, as the result is rounded down.

The integer division can be done on Python 3 too, with // operator, thus to get the 7 as a result, you can execute:

3 + 2 + 1 - 5 + 4 % 2 - 1 // 4 + 6

Also, you can get the Python style division on Python 2, by just adding the line

from __future__ import division

as the first source code line in each source file.


回答 8

模运算符,通常用于整数的余数除法,但在Python中可用于浮点数。

http://docs.python.org/reference/expressions.html

%(模)运算符从第一个参数除以第二个参数得出余数。首先将数字参数转换为通用类型。零权限参数引发ZeroDivisionError异常。参数可以是浮点数,例如3.14%0.7等于0.34(因为3.14等于4 * 0.7 + 0.34。)模运算符始终产生与第二个操作数具有相同符号的结果(或为零);结果的绝对值严格小于第二个操作数的绝对值[2]。

Modulus operator, it is used for remainder division on integers, typically, but in Python can be used for floating point numbers.

http://docs.python.org/reference/expressions.html

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].


回答 9

这是一个模运算,除了它是老式的C风格的字符串格式化运算符,而不是模运算。有关详细信息,请参见此处。您将在现有代码中看到很多这样的内容。

It’s a modulo operation, except when it’s an old-fashioned C-style string formatting operator, not a modulo operation. See here for details. You’ll see a lot of this in existing code.


回答 10

此外,还有一个有用的内置函数,称为divmod

divmod(a,b)

使用两个(非复数)数字作为参数,并在使用长除法时返回一对包含其商和余数的数字。

Also, there is a useful built-in function called divmod:

divmod(a, b)

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division.


回答 11

意识到

(3 +2 + 1 - 5) + (4 % 2) - (1/4) + 6

如果使用Python 3.4计算,即使带括号的结果也是6.75,而不是7。


而且’/’运算符也不是那么容易理解(python2.7):试试…

- 1/4

1 - 1/4

这里有点题外话,但是在评估上面的表达式时应该考虑:)

Be aware that

(3 +2 + 1 - 5) + (4 % 2) - (1/4) + 6

even with the brackets results in 6.75 instead of 7 if calculated in Python 3.4.


And the ‘/’ operator is not that easy to understand, too (python2.7): try…

- 1/4

1 - 1/4

This is a bit off-topic here, but should be considered when evaluating the above expression :)


回答 12

对于我来说,很难在线找到使用%的特定用例,例如,为什么做分数模除法或负模除法会得出答案呢?希望这有助于澄清如下问题:

模量部门:

模除法返回数学除法运算的余数。这样做如下:

假设我们的股息为5,除数为2,则以下除法运算将等于(等于x):

dividend = 5
divisor = 2

x = 5/2 
  1. 模量计算的第一步是进行整数除法:

    x_int = 5 // 2(Python中的整数除法使用双斜杠)

    x_int = 2

  2. 接下来,x_int的输出乘以除数:

    x_mult = x_int *除数x_mult = 4

  3. 最后,从x_mult中减去股息

    红利-x_mult = 1

  4. 模运算,因此返回1:

    5%2 = 1

申请将模数应用于分数

Example: 2 % 5 

当应用于分数时,模量的计算与上面相同;但是,重要的是要注意,当除数大于被除数时,整数除法将得出零值:

dividend = 2 
divisor = 5

整数除法得出0,而; 因此,当执行上面的步骤3时,将计算分红的值(减去零):

dividend - 0 = 2  —> 2 % 5 = 2 

申请将模数应用于负数

发生地板除法,其中整数除法的值四舍五入到最低整数值:

import math 

x = -1.1
math.floor(-1.1) = -2 

y = 1.1
math.floor = 1

因此,当您进行整数除法时,您可能会得到与预期不同的结果!

将以上步骤应用于以下除数和除数可以说明模量概念:

dividend: -5 
divisor: 2 

步骤1:应用整数除法

x_int = -5 // 2  = -3

步骤2:将整数除法的结果乘以除数

x_mult = x_int * 2 = -6

步骤3:从乘法变量中减去红利,请注意双负数。

dividend - x_mult = -5 -(-6) = 1

因此:

-5 % 2 = 1

It was hard for me to readily find specific use cases for the use of % online ,e.g. why does doing fractional modulus division or negative modulus division result in the answer that it does. Hope this helps clarify questions like this:

Modulus Division In General:

Modulus division returns the remainder of a mathematical division operation. It is does it as follows:

Say we have a dividend of 5 and divisor of 2, the following division operation would be (equated to x):

dividend = 5
divisor = 2

x = 5/2 
  1. The first step in the modulus calculation is to conduct integer division:

    x_int = 5 // 2 ( integer division in python uses double slash)

    x_int = 2

  2. Next, the output of x_int is multiplied by the divisor:

    x_mult = x_int * divisor x_mult = 4

  3. Lastly, the dividend is subtracted from the x_mult

    dividend – x_mult = 1

  4. The modulus operation ,therefore, returns 1:

    5 % 2 = 1

Application to apply the modulus to a fraction

Example: 2 % 5 

The calculation of the modulus when applied to a fraction is the same as above; however, it is important to note that the integer division will result in a value of zero when the divisor is larger than the dividend:

dividend = 2 
divisor = 5

The integer division results in 0 whereas the; therefore, when step 3 above is performed, the value of the dividend is carried through (subtracted from zero):

dividend - 0 = 2  —> 2 % 5 = 2 

Application to apply the modulus to a negative

Floor division occurs in which the value of the integer division is rounded down to the lowest integer value:

import math 

x = -1.1
math.floor(-1.1) = -2 

y = 1.1
math.floor = 1

Therefore, when you do integer division you may get a different outcome than you expect!

Applying the steps above on the following dividend and divisor illustrates the modulus concept:

dividend: -5 
divisor: 2 

Step 1: Apply integer division

x_int = -5 // 2  = -3

Step 2: Multiply the result of the integer division by the divisor

x_mult = x_int * 2 = -6

Step 3: Subtract the dividend from the multiplied variable, notice the double negative.

dividend - x_mult = -5 -(-6) = 1

Therefore:

-5 % 2 = 1

回答 13

%(模)运算符从第一个参数除以第二个参数得出余数。首先将数字参数转换为通用类型。

3 + 2 + 1-5 + 4%2-1/4 + 6 = 7

这基于运算符优先级。

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type.

3 + 2 + 1 – 5 + 4 % 2 – 1 / 4 + 6 = 7

This is based on operator precedence.


回答 14

%3 % 2 = 14 % 2 = 0

/ 是(在这种情况下为整数)除,因此:

3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
1 + 4%2 - 1/4 + 6
1 + 0 - 0 + 6
7

% is modulo. 3 % 2 = 1, 4 % 2 = 0

/ is (an integer in this case) division, so:

3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
1 + 4%2 - 1/4 + 6
1 + 0 - 0 + 6
7

回答 15

这是模运算 http://en.wikipedia.org/wiki/Modulo_operation

http://docs.python.org/reference/expressions.html

因此,按照操作顺序,

(3 + 2 + 1-5)+(4%2)-(1/4)+ 6

(1)+(0)-(0)+ 6

7

1/4 = 0,因为我们在这里进行整数运算。

It’s a modulo operation http://en.wikipedia.org/wiki/Modulo_operation

http://docs.python.org/reference/expressions.html

So with order of operations, that works out to

(3+2+1-5) + (4%2) – (1/4) + 6

(1) + (0) – (0) + 6

7

The 1/4=0 because we’re doing integer math here.


回答 16

就像许多类似C的语言一样,它是余数或模运算。有关数字类型信息,请参见文档-int,float,long,complex

It is, as in many C-like languages, the remainder or modulo operation. See the documentation for numeric types — int, float, long, complex.


回答 17

模数-左操作数除以右操作数,并返回余数。

如果有帮助:

1:0> 2%6
=> 2
2:0> 8%6
=> 2
3:0> 2%6 == 8%6
=> true

… 等等。

Modulus – Divides left hand operand by right hand operand and returns remainder.

If it helps:

1:0> 2%6
=> 2
2:0> 8%6
=> 2
3:0> 2%6 == 8%6
=> true

… and so on.


回答 18

我发现掌握模数运算符(%)的最简单方法是进行长除法。它是余数,可用于确定数字是偶数还是奇数:

4%2 = 0

  2
2|4
 -4
  0


11%3 = 2

  3
3|11
 -9
  2

I have found that the easiest way to grasp the modulus operator (%) is through long division. It is the remainder and can be useful in determining a number to be even or odd:

4%2 = 0

  2
2|4
 -4
  0


11%3 = 2

  3
3|11
 -9
  2

为什么我的Pandas的“应用”功能不能引用多个列?[关闭]

问题:为什么我的Pandas的“应用”功能不能引用多个列?[关闭]

当将多个列与以下数据框一起使用时,Pandas Apply函数存在一些问题

df = DataFrame ({'a' : np.random.randn(6),
                 'b' : ['foo', 'bar'] * 3,
                 'c' : np.random.randn(6)})

和以下功能

def my_test(a, b):
    return a % b

当我尝试使用以下功能时:

df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1)

我收到错误消息:

NameError: ("global name 'a' is not defined", u'occurred at index 0')

我不明白此消息,我正确定义了名称。

非常感谢您对此问题的帮助

更新资料

谢谢你的帮助。我确实在代码中犯了一些语法错误,索引应该放在”。但是,使用更复杂的功能仍然会遇到相同的问题,例如:

def my_test(a):
    cum_diff = 0
    for ix in df.index():
        cum_diff = cum_diff + (a - df['a'][ix])
    return cum_diff 

I have some problems with the Pandas apply function, when using multiple columns with the following dataframe

df = DataFrame ({'a' : np.random.randn(6),
                 'b' : ['foo', 'bar'] * 3,
                 'c' : np.random.randn(6)})

and the following function

def my_test(a, b):
    return a % b

When I try to apply this function with :

df['Value'] = df.apply(lambda row: my_test(row[a], row[c]), axis=1)

I get the error message:

NameError: ("global name 'a' is not defined", u'occurred at index 0')

I do not understand this message, I defined the name properly.

I would highly appreciate any help on this issue

Update

Thanks for your help. I made indeed some syntax mistakes with the code, the index should be put ”. However I still get the same issue using a more complex function such as:

def my_test(a):
    cum_diff = 0
    for ix in df.index():
        cum_diff = cum_diff + (a - df['a'][ix])
    return cum_diff 

回答 0

好像您忘记了''字符串。

In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)

In [44]: df
Out[44]:
                    a    b         c     Value
          0 -1.674308  foo  0.343801  0.044698
          1 -2.163236  bar -2.046438 -0.116798
          2 -0.199115  foo -0.458050 -0.199115
          3  0.918646  bar -0.007185 -0.001006
          4  1.336830  foo  0.534292  0.268245
          5  0.976844  bar -0.773630 -0.570417

在我看来,顺便说一句,以下方式更为优雅:

In [53]: def my_test2(row):
....:     return row['a'] % row['c']
....:     

In [54]: df['Value'] = df.apply(my_test2, axis=1)

Seems you forgot the '' of your string.

In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)

In [44]: df
Out[44]:
                    a    b         c     Value
          0 -1.674308  foo  0.343801  0.044698
          1 -2.163236  bar -2.046438 -0.116798
          2 -0.199115  foo -0.458050 -0.199115
          3  0.918646  bar -0.007185 -0.001006
          4  1.336830  foo  0.534292  0.268245
          5  0.976844  bar -0.773630 -0.570417

BTW, in my opinion, following way is more elegant:

In [53]: def my_test2(row):
....:     return row['a'] % row['c']
....:     

In [54]: df['Value'] = df.apply(my_test2, axis=1)

回答 1

如果您只想计算(a栏)%(b栏),则不需要apply,只需直接执行:

In [7]: df['a'] % df['c']                                                                                                                                                        
Out[7]: 
0   -1.132022                                                                                                                                                                    
1   -0.939493                                                                                                                                                                    
2    0.201931                                                                                                                                                                    
3    0.511374                                                                                                                                                                    
4   -0.694647                                                                                                                                                                    
5   -0.023486                                                                                                                                                                    
Name: a

If you just want to compute (column a) % (column b), you don’t need apply, just do it directly:

In [7]: df['a'] % df['c']                                                                                                                                                        
Out[7]: 
0   -1.132022                                                                                                                                                                    
1   -0.939493                                                                                                                                                                    
2    0.201931                                                                                                                                                                    
3    0.511374                                                                                                                                                                    
4   -0.694647                                                                                                                                                                    
5   -0.023486                                                                                                                                                                    
Name: a

回答 2

假设我们要对DataFrame df的列“ a”和“ b”应用add5函数

def add5(x):
    return x+5

df[['a', 'b']].apply(add5)

Let’s say we want to apply a function add5 to columns ‘a’ and ‘b’ of DataFrame df

def add5(x):
    return x+5

df[['a', 'b']].apply(add5)

回答 3

以上所有建议均有效,但如果您希望提高计算效率,则应利用numpy向量运算(如此处所述)

import pandas as pd
import numpy as np


df = pd.DataFrame ({'a' : np.random.randn(6),
             'b' : ['foo', 'bar'] * 3,
             'c' : np.random.randn(6)})

示例1:循环pandas.apply()

%%timeit
def my_test2(row):
    return row['a'] % row['c']

df['Value'] = df.apply(my_test2, axis=1)

最慢的运行时间比最快的运行时间长7.49倍。这可能意味着正在缓存中间结果。1000个循环,最佳3:每个循环481 µs

示例2:使用进行矢量化pandas.apply()

%%timeit
df['a'] % df['c']

最慢的运行时间比最快的运行时间长458.85倍。这可能意味着正在缓存中间结果。10000次循环,最好为3次:每个循环70.9 µs

示例3:使用numpy数组进行向量化:

%%timeit
df['a'].values % df['c'].values

最慢的运行时间比最快的运行时间长7.98倍。这可能意味着正在缓存中间结果。100000次循环,每循环3:6.39 µs最佳

因此,使用numpy数组进行向量化将速度提高了近两个数量级。

All of the suggestions above work, but if you want your computations to by more efficient, you should take advantage of numpy vector operations (as pointed out here).

import pandas as pd
import numpy as np


df = pd.DataFrame ({'a' : np.random.randn(6),
             'b' : ['foo', 'bar'] * 3,
             'c' : np.random.randn(6)})

Example 1: looping with pandas.apply():

%%timeit
def my_test2(row):
    return row['a'] % row['c']

df['Value'] = df.apply(my_test2, axis=1)

The slowest run took 7.49 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 481 µs per loop

Example 2: vectorize using pandas.apply():

%%timeit
df['a'] % df['c']

The slowest run took 458.85 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 70.9 µs per loop

Example 3: vectorize using numpy arrays:

%%timeit
df['a'].values % df['c'].values

The slowest run took 7.98 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 6.39 µs per loop

So vectorizing using numpy arrays improved the speed by almost two orders of magnitude.


回答 4

这与先前的解决方案相同,但是我已经在df.apply本身中定义了该函数:

df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1)

This is same as the previous solution but I have defined the function in df.apply itself:

df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1)

回答 5

我已经比较了上面讨论的所有三个。

使用值

%timeit df ['value'] = df ['a']。values%df ['c']。values

每个回路139 µs±1.91 µs(平均±标准偏差,共运行7次,每个回路10000个)

没有价值

%timeit df ['value'] = df ['a']%df ['c'] 

每个循环216 µs±1.86 µs(平均±标准偏差,共运行7次,每个循环1000个)

套用功能

%timeit df ['Value'] = df.apply(lambda row:row ['a']%row ['c'],axis = 1)

每个回路474 µs±5.07 µs(平均±标准偏差,共运行7次,每个回路1000个)

I have given the comparison of all three discussed above.

Using values

%timeit df['value'] = df['a'].values % df['c'].values

139 µs ± 1.91 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Without values

%timeit df['value'] = df['a']%df['c'] 

216 µs ± 1.86 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Apply function

%timeit df['Value'] = df.apply(lambda row: row['a']%row['c'], axis=1)

474 µs ± 5.07 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


在Python中,如何将“ datetime”对象转换为秒?

问题:在Python中,如何将“ datetime”对象转换为秒?

为这个简单的问题表示歉意…我是Python的新手…我四处搜寻,似乎没有任何反应。

我有一堆datetime对象,我想计算每个对象过去某个固定时间以来的秒数(例如,自1970年1月1日起)。

import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)

这似乎只能区分具有不同日期的日期:

t.toordinal()

任何帮助深表感谢。

Apologies for the simple question… I’m new to Python… I have searched around and nothing seems to be working.

I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).

import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)

This seems to be only differentiating between dates that have different days:

t.toordinal()

Any help is much appreciated.


回答 0

在1970年1月1日这个特殊日期,有多种选择。

对于任何其他开始日期,您需要以秒为单位获取两个日期之间的差额。将两个日期相减得到一个timedelta对象,从Python 2.7开始,该对象具有total_seconds()功能。

>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0

通常以UTC指定开始日期,因此,要获得正确的结果,datetime您也应使用UTC输入该公式。如果您datetime尚未使用UTC,则需要先进行转换,再使用它,或附加tzinfo具有适当偏移量的类。

如评论中所述,如果您有tzinfo附件,datetime则在开始日期也需要一个附件,否则减法将会失败;对于上面的示例,tzinfo=pytz.utc如果使用Python 2或tzinfo=timezone.utcPython 3 ,我会添加。

For the special date of January 1, 1970 there are multiple options.

For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a timedelta object, which as of Python 2.7 has a total_seconds() function.

>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0

The starting date is usually specified in UTC, so for proper results the datetime you feed into this formula should be in UTC as well. If your datetime isn’t in UTC already, you’ll need to convert it before you use it, or attach a tzinfo class that has the proper offset.

As noted in the comments, if you have a tzinfo attached to your datetime then you’ll need one on the starting date as well or the subtraction will fail; for the example above I would add tzinfo=pytz.utc if using Python 2 or tzinfo=timezone.utc if using Python 3.


回答 1

要获取Unix时间(自1970年1月1日以来的秒数):

>>> import datetime, time
>>> t = datetime.datetime(2011, 10, 21, 0, 0)
>>> time.mktime(t.timetuple())
1319148000.0

To get the Unix time (seconds since January 1, 1970):

>>> import datetime, time
>>> t = datetime.datetime(2011, 10, 21, 0, 0)
>>> time.mktime(t.timetuple())
1319148000.0

回答 2

从Python 3.3开始,使用此datetime.timestamp()方法变得非常容易。当然,这仅在需要从1970-01-01 UTC开始的秒数时才有用。

from datetime import datetime
dt = datetime.today()  # Get timezone naive now
seconds = dt.timestamp()

返回值将是代表偶数秒的浮点数。如果datetime是时区朴素的(如上例所示),则将假定datetime对象代表本地时间,即,它是从您所在位置的当前时间到1970-01-01 UTC的秒数。

Starting from Python 3.3 this becomes super easy with the datetime.timestamp() method. This of course will only be useful if you need the number of seconds from 1970-01-01 UTC.

from datetime import datetime
dt = datetime.today()  # Get timezone naive now
seconds = dt.timestamp()

The return value will be a float representing even fractions of a second. If the datetime is timezone naive (as in the example above), it will be assumed that the datetime object represents the local time, i.e. It will be the number of seconds from current time at your location to 1970-01-01 UTC.


回答 3

也许离题:从日期时间获取UNIX / POSIX时间并将其转换回:

>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0

# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)

请注意,不同的时区会影响结果,例如我当前的TZ / DST返回:

>>>  time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h

因此,应该考虑使用功能的UTC版本将其标准化为UTC。

请注意,先前的结果可用于计算您当前时区的UTC偏移量。在此示例中,这是+1小时,即UTC + 0100。

参考文献:

Maybe off-the-topic: to get UNIX/POSIX time from datetime and convert it back:

>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0

# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)

Note that different timezones have impact on results, e.g. my current TZ/DST returns:

>>>  time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h

therefore one should consider normalizing to UTC by using UTC versions of the functions.

Note that previous result can be used to calculate UTC offset of your current timezone. In this example this is +1h, i.e. UTC+0100.

References:


回答 4

int (t.strftime("%s")) 也可以

int (t.strftime("%s")) also works


回答 5

从python文档:

timedelta.total_seconds()

返回持续时间中包含的总秒数。相当于

(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

在启用真除法的情况下进行计算。

请注意,对于非常长的时间间隔(在大多数平台上大于270年),此方法将失去微秒的精度。

此功能是2.7版中的新增功能。

from the python docs:

timedelta.total_seconds()

Return the total number of seconds contained in the duration. Equivalent to

(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

computed with true division enabled.

Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.

This functionality is new in version 2.7.


回答 6

要将代表UTC时间的datetime对象转换为POSIX时间戳

from datetime import timezone

seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp()

要将代表本地时区中时间的datetime对象转换为POSIX时间戳,请执行以下操作:

import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp()

请参阅如何在Python中将本地时间转换为UTC?如果tz数据库在给定平台上可用;仅有stdlib的解决方案可能有效

如果您需要<3.3Python版本的解决方案,请点击链接。

To convert a datetime object that represents time in UTC to POSIX timestamp:

from datetime import timezone

seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp()

To convert a datetime object that represents time in the local timezone to POSIX timestamp:

import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp()

See How do I convert local time to UTC in Python? If the tz database is available on a given platform; a stdlib-only solution may work.

Follow the links if you need solutions for <3.3 Python versions.


回答 7

我尝试了标准库的calendar.timegm,它工作得很好:

# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
    return int(calendar.timegm(aDateTime.timetuple())*1000)

参考:https : //docs.python.org/2/library/calendar.html#calendar.timegm

I tried the standard library’s calendar.timegm and it works quite well:

# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
    return int(calendar.timegm(aDateTime.timetuple())*1000)

Ref: https://docs.python.org/2/library/calendar.html#calendar.timegm


如何在Python 2.7中隐藏子进程的输出

问题:如何在Python 2.7中隐藏子进程的输出

我在Ubuntu上使用eSpeak,并且有一个Python 2.7脚本可以打印和显示一条消息:

import subprocess
text = 'Hello World.'
print text
subprocess.call(['espeak', text])

eSpeak产生所需的声音,但由于一些错误(ALSA lib …,没有套接字连接)而使外壳混乱,因此我无法轻松读取之前打印的内容。退出代码为0。

不幸的是,没有记录的选项可以关闭其详细信息,因此我正在寻找一种方法,仅在视觉上使其静音并保持打开的外壳干净以进行进一步的交互。

我怎样才能做到这一点?

I’m using eSpeak on Ubuntu and have a Python 2.7 script that prints and speaks a message:

import subprocess
text = 'Hello World.'
print text
subprocess.call(['espeak', text])

eSpeak produces the desired sounds, but clutters the shell with some errors (ALSA lib…, no socket connect) so i cannot easily read what was printed earlier. Exit code is 0.

Unfortunately there is no documented option to turn off its verbosity, so I’m looking for a way to only visually silence it and keep the open shell clean for further interaction.

How can I do this?


回答 0

将输出重定向到DEVNULL:

import os
import subprocess

FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'], stdout=FNULL, stderr=subprocess.STDOUT)

它实际上与运行此shell命令相同:

retcode = os.system("echo 'foo' &> /dev/null")

Redirect the output to DEVNULL:

import os
import subprocess

FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'], 
    stdout=FNULL, 
    stderr=subprocess.STDOUT)

It is effectively the same as running this shell command:

retcode = os.system("echo 'foo' &> /dev/null")

Update: This answer applies to the original question relating to python 2.7. As of python >= 3.3 an official subprocess.DEVNULL symbol was added.

retcode = subprocess.call(['echo', 'foo'], 
    stdout=subprocess.DEVNULL, 
    stderr=subprocess.STDOUT)

回答 1

这是一个更便携的版本(只是为了好玩,在您的情况下没有必要):

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE, STDOUT

try:
    from subprocess import DEVNULL # py3k
except ImportError:
    import os
    DEVNULL = open(os.devnull, 'wb')

text = u"René Descartes"
p = Popen(['espeak', '-b', '1'], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
p.communicate(text.encode('utf-8'))
assert p.returncode == 0 # use appropriate for your program error handling here

Here’s a more portable version (just for fun, it is not necessary in your case):

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE, STDOUT

try:
    from subprocess import DEVNULL # py3k
except ImportError:
    import os
    DEVNULL = open(os.devnull, 'wb')

text = u"René Descartes"
p = Popen(['espeak', '-b', '1'], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
p.communicate(text.encode('utf-8'))
assert p.returncode == 0 # use appropriate for your program error handling here

回答 2

使用subprocess.check_output(python 2.7中的新功能)。如果命令失败,它将抑制stdout并引发异常。(它实际上返回stdout的内容,因此您可以在以后的程序中使用它。)例如:

import subprocess
try:
    subprocess.check_output(['espeak', text])
except subprocess.CalledProcessError:
    # Do something

您还可以使用以下命令抑制stderr:

    subprocess.check_output(["espeak", text], stderr=subprocess.STDOUT)

对于2.7之前的版本,请使用

import os
import subprocess
with open(os.devnull, 'w')  as FNULL:
    try:
        subprocess._check_call(['espeak', text], stdout=FNULL)
    except subprocess.CalledProcessError:
        # Do something

在这里,您可以使用

        subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)

Use subprocess.check_output (new in python 2.7). It will suppress stdout and raise an exception if the command fails. (It actually returns the contents of stdout, so you can use that later in your program if you want.) Example:

import subprocess
try:
    subprocess.check_output(['espeak', text])
except subprocess.CalledProcessError:
    # Do something

You can also suppress stderr with:

    subprocess.check_output(["espeak", text], stderr=subprocess.STDOUT)

For earlier than 2.7, use

import os
import subprocess
with open(os.devnull, 'w')  as FNULL:
    try:
        subprocess._check_call(['espeak', text], stdout=FNULL)
    except subprocess.CalledProcessError:
        # Do something

Here, you can suppress stderr with

        subprocess._check_call(['espeak', text], stdout=FNULL, stderr=FNULL)

回答 3

由于Python3你不再需要打开devnull并且可以调用subprocess.DEVNULL

您的代码将这样更新:

import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)

As of Python3 you no longer need to open devnull and can call subprocess.DEVNULL.

Your code would be updated as such:

import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)

回答 4

为什么不使用commands.getoutput()代替呢?

import commands

text = "Mario Balotelli" 
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)

Why not use commands.getoutput() instead?

import commands

text = "Mario Balotelli" 
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)

如何将输入读取为数字?

问题:如何将输入读取为数字?

为什么在下面的代码中使用xy字符串而不是整数?

(注意:在Python 2.x中使用raw_input()。在Python 3.x中使用input()。在Python 3.x中raw_input()被重命名为input()

play = True

while play:

    x = input("Enter a number: ")
    y = input("Enter a number: ")

    print(x + y)
    print(x - y)
    print(x * y)
    print(x / y)
    print(x % y)

    if input("Play again? ") == "no":
        play = False

Why are x and y strings instead of ints in the below code?

(Note: in Python 2.x use raw_input(). In Python 3.x use input(). raw_input() was renamed to input() in Python 3.x)

play = True

while play:

    x = input("Enter a number: ")
    y = input("Enter a number: ")

    print(x + y)
    print(x - y)
    print(x * y)
    print(x / y)
    print(x % y)

    if input("Play again? ") == "no":
        play = False

回答 0

TLDR

  • Python 3不会评估input函数接收到的数据,但是Python 2的input函数会评估(阅读下一节以了解含义)。
  • inputraw_input函数相当于Python 2与Python 3 。

Python 2.x

有两个函数用于获取用户输入,分别称为inputraw_input。它们之间的区别是,raw_input不评估数据并以字符串形式按原样返回。但是,input将对您输入的内容进行评估,评估结果将返回。例如,

>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

5 + 17评估数据,结果为22。当它对表达式求值时5 + 17,它将检测到您要添加两个数字,因此结果也将是同一int类型。因此,类型转换是免费完成的,并22作为的结果返回input并存储在data变量中。您可以将其input视为raw_input带有eval调用的组合。

>>> data = eval(raw_input("Enter a number: "))
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

注意:input在Python 2.x 中使用时应小心。我在这个答案中解释了为什么在使用它时要小心。

但是,raw_input不评估输入并以字符串形式原样返回。

>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = raw_input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <type 'str'>)

Python 3.x

Python 3.x input和Python 2.x raw_input类似,raw_input在Python 3.x中不可用。

>>> import sys
>>> sys.version
'3.4.0 (default, Apr 11 2014, 13:05:11) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <class 'str'>)

要回答您的问题,由于Python 3.x不会评估和转换数据类型,因此必须使用显式转换为ints int,如下所示

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

您可以接受任意基数的数字,并使用int函数将其直接转换为10基数

>>> data = int(input("Enter a number: "), 8)
Enter a number: 777
>>> data
511
>>> data = int(input("Enter a number: "), 16)
Enter a number: FFFF
>>> data
65535
>>> data = int(input("Enter a number: "), 2)
Enter a number: 10101010101
>>> data
1365

第二个参数告诉输入的数字的基础是什么,然后在内部对其进行理解和转换。如果输入的数据有误,将抛出ValueError

>>> data = int(input("Enter a number: "), 2)
Enter a number: 1234
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '1234'

对于可以包含小数部分的值,类型应为float而不是int

x = float(input("Enter a number:"))

除此之外,您的程序可以像这样进行一些更改

while True:
    ...
    ...
    if input("Play again? ") == "no":
        break

您可以play使用break和摆脱变量while True

TLDR

  • Python 3 doesn’t evaluate the data received with input function, but Python 2’s input function does (read the next section to understand the implication).
  • Python 2’s equivalent of Python 3’s input is the raw_input function.

Python 2.x

There were two functions to get user input, called input and raw_input. The difference between them is, raw_input doesn’t evaluate the data and returns as it is, in string form. But, input will evaluate whatever you entered and the result of evaluation will be returned. For example,

>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

The data 5 + 17 is evaluated and the result is 22. When it evaluates the expression 5 + 17, it detects that you are adding two numbers and so the result will also be of the same int type. So, the type conversion is done for free and 22 is returned as the result of input and stored in data variable. You can think of input as the raw_input composed with an eval call.

>>> data = eval(raw_input("Enter a number: "))
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

Note: you should be careful when you are using input in Python 2.x. I explained why one should be careful when using it, in this answer.

But, raw_input doesn’t evaluate the input and returns as it is, as a string.

>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = raw_input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <type 'str'>)

Python 3.x

Python 3.x’s input and Python 2.x’s raw_input are similar and raw_input is not available in Python 3.x.

>>> import sys
>>> sys.version
'3.4.0 (default, Apr 11 2014, 13:05:11) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <class 'str'>)

Solution

To answer your question, since Python 3.x doesn’t evaluate and convert the data type, you have to explicitly convert to ints, with int, like this

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

You can accept numbers of any base and convert them directly to base-10 with the int function, like this

>>> data = int(input("Enter a number: "), 8)
Enter a number: 777
>>> data
511
>>> data = int(input("Enter a number: "), 16)
Enter a number: FFFF
>>> data
65535
>>> data = int(input("Enter a number: "), 2)
Enter a number: 10101010101
>>> data
1365

The second parameter tells what is the base of the numbers entered and then internally it understands and converts it. If the entered data is wrong it will throw a ValueError.

>>> data = int(input("Enter a number: "), 2)
Enter a number: 1234
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '1234'

For values that can have a fractional component, the type would be float rather than int:

x = float(input("Enter a number:"))

Apart from that, your program can be changed a little bit, like this

while True:
    ...
    ...
    if input("Play again? ") == "no":
        break

You can get rid of the play variable by using break and while True.


回答 1

在Python 3.x中,raw_input已重命名为,inputinput删除了Python2.x 。

这意味着,就像Python 3.x中的一样raw_inputinput总是返回一个字符串对象。

要解决此问题,您需要通过将它们输入以下内容来将这些输入明确地变成整数int

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

In Python 3.x, raw_input was renamed to input and the Python 2.x input was removed.

This means that, just like raw_input, input in Python 3.x always returns a string object.

To fix the problem, you need to explicitly make those inputs into integers by putting them in int:

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

回答 2

对于单行中的多个整数,map可能会更好。

arr = map(int, raw_input().split())

如果数字已知(例如2个整数),则可以使用

num1, num2 = map(int, raw_input().split())

For multiple integer in a single line, map might be better.

arr = map(int, raw_input().split())

If the number is already known, (like 2 integers), you can use

num1, num2 = map(int, raw_input().split())

回答 3

input()(Python 3)和raw_input()(Python 2)始终返回字符串。使用显式将结果转换为整数int()

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

input() (Python 3) and raw_input() (Python 2) always return strings. Convert the result to integer explicitly with int().

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

回答 4

多个问题需要在单行上输入多个整数。最好的方法是一行输入整个数字字符串,然后将它们拆分为整数。这是Python 3版本:

a = []
p = input()
p = p.split()      
for i in p:
    a.append(int(i))

也可以使用列表理解

p = input().split("whatever the seperator is")

并将所有输入从字符串转换为整数,我们执行以下操作

x = [int(i) for i in p]
print(x, end=' ')

应以直线打印列表元素。

Multiple questions require input for several integers on single line. The best way is to input the whole string of numbers one one line and then split them to integers. Here is a Python 3 version:

a = []
p = input()
p = p.split()      
for i in p:
    a.append(int(i))

Also a list comprehension can be used

p = input().split("whatever the seperator is")

And to convert all the inputs from string to int we do the following

x = [int(i) for i in p]
print(x, end=' ')

shall print the list elements in a straight line.


回答 5

转换为整数:

my_number = int(input("enter the number"))

对于浮点数类似:

my_decimalnumber = float(input("enter the number"))

Convert to integers:

my_number = int(input("enter the number"))

Similarly for floating point numbers:

my_decimalnumber = float(input("enter the number"))

回答 6

n=int(input())
for i in range(n):
    n=input()
    n=int(n)
    arr1=list(map(int,input().split()))

for循环应运行’n’次。第二个“ n”是数组的长度。最后一条语句将整数映射到列表,并以空格分隔的形式接受输入。您还可以在for循环的末尾返回数组。

n=int(input())
for i in range(n):
    n=input()
    n=int(n)
    arr1=list(map(int,input().split()))

the for loop shall run ‘n’ number of times . the second ‘n’ is the length of the array. the last statement maps the integers to a list and takes input in space separated form . you can also return the array at the end of for loop.


回答 7

我在解决CodeChef上的问题时遇到了输入整数的问题,该问题应从一行读取两个以空格分隔的整数。

虽然int(input())对于单个整数就足够了,但是我没有找到直接输入两个整数的方法。我尝试了这个:

num = input()
num1 = 0
num2 = 0

for i in range(len(num)):
    if num[i] == ' ':
        break

num1 = int(num[:i])
num2 = int(num[i+1:])

现在,我将num1和num2用作整数。希望这可以帮助。

I encountered a problem of taking integer input while solving a problem on CodeChef, where two integers – separated by space – should be read from one line.

While int(input()) is sufficient for a single integer, I did not find a direct way to input two integers. I tried this:

num = input()
num1 = 0
num2 = 0

for i in range(len(num)):
    if num[i] == ' ':
        break

num1 = int(num[:i])
num2 = int(num[i+1:])

Now I use num1 and num2 as integers. Hope this helps.


回答 8

def dbz():
    try:
        r = raw_input("Enter number:")
        if r.isdigit():
            i = int(raw_input("Enter divident:"))
            d = int(r)/i
            print "O/p is -:",d
        else:
            print "Not a number"
    except Exception ,e:
        print "Program halted incorrect data entered",type(e)
dbz()

Or 

num = input("Enter Number:")#"input" will accept only numbers
def dbz():
    try:
        r = raw_input("Enter number:")
        if r.isdigit():
            i = int(raw_input("Enter divident:"))
            d = int(r)/i
            print "O/p is -:",d
        else:
            print "Not a number"
    except Exception ,e:
        print "Program halted incorrect data entered",type(e)
dbz()

Or 

num = input("Enter Number:")#"input" will accept only numbers

回答 9

尽管在你的榜样,int(input(...))做的伎俩在任何情况下,python-futurebuiltins.input是值得考虑的,因为这可以确保你的代码同时适用于Python 2和3 ,并禁用Python2的违约行为,input努力成为‘聪明的’关于输入数据类型(builtins.input基本上只是的行为类似于raw_input)。

While in your example, int(input(...)) does the trick in any case, python-future‘s builtins.input is worth consideration since that makes sure your code works for both Python 2 and 3 and disables Python2’s default behaviour of input trying to be “clever” about the input data type (builtins.input basically just behaves like raw_input).


如何在python中获取当前时间并分解为年,月,日,小时,分钟?

问题:如何在python中获取当前时间并分解为年,月,日,小时,分钟?

我想获得当前时间在Python,并将它们分配到变量喜欢yearmonthdayhourminute。如何在Python 2.7中完成?

I would like to get the current time in Python and assign them into variables like year, month, day, hour, minute. How can this be done in Python 2.7?


回答 0

datetime模块是您的朋友:

import datetime
now = datetime.datetime.now()
print now.year, now.month, now.day, now.hour, now.minute, now.second
# 2015 5 6 8 53 40

您不需要单独的变量,返回datetime对象上的属性就可以满足您的所有需求。

The datetime module is your friend:

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40

You don’t need separate variables, the attributes on the returned datetime object have all you need.


回答 1

这是一个单线,最大字符数不超过80个字符。

import time
year, month, day, hour, min = map(int, time.strftime("%Y %m %d %H %M").split())

Here’s a one-liner that comes in just under the 80 char line max.

import time
year, month, day, hour, min = map(int, time.strftime("%Y %m %d %H %M").split())

回答 2

tzamandatetime答案要干净得多,但是您可以使用原始的python 模块来实现:time

import time
strings = time.strftime("%Y,%m,%d,%H,%M,%S")
t = strings.split(',')
numbers = [ int(x) for x in t ]
print numbers

输出:

[2016, 3, 11, 8, 29, 47]

The datetime answer by tzaman is much cleaner, but you can do it with the original python time module:

import time
strings = time.strftime("%Y,%m,%d,%H,%M,%S")
t = strings.split(',')
numbers = [ int(x) for x in t ]
print numbers

Output:

[2016, 3, 11, 8, 29, 47]

回答 3

通过解压缩timetupledatetime对象,您应该得到想要的东西:

from datetime import datetime

n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t

By unpacking timetuple of datetime object, you should get what you want:

from datetime import datetime

n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t

回答 4

对于python 3

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)

For python 3

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)

回答 5

让我们看看如何从当前时间获取并打印python中的日,月,年:

import datetime

now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)

print('day_month_year: ' + day_month_year)

结果:

day_month_year: 2019-03-26

Let’s see how to get and print day,month,year in python from current time:

import datetime

now = datetime.datetime.now()
year = '{:02d}'.format(now.year)
month = '{:02d}'.format(now.month)
day = '{:02d}'.format(now.day)
hour = '{:02d}'.format(now.hour)
minute = '{:02d}'.format(now.minute)
day_month_year = '{}-{}-{}'.format(year, month, day)

print('day_month_year: ' + day_month_year)

result:

day_month_year: 2019-03-26

回答 6

import time
year = time.strftime("%Y") # or "%y"
import time
year = time.strftime("%Y") # or "%y"

回答 7

三个用于访问和操纵日期和时间的库,即日期时间,箭头和摆锤,都使这些项在命名元组中可用,命名元组的元素可通过名称或索引访问。此外,可以完全相同的方式访问项目。(我想如果我更聪明,我不会感到惊讶。)

>>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5)
>>> import datetime
>>> import arrow
>>> import pendulum
>>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 16]

Three libraries for accessing and manipulating dates and times, namely datetime, arrow and pendulum, all make these items available in namedtuples whose elements are accessible either by name or index. Moreover, the items are accessible in precisely the same way. (I suppose if I were more intelligent I wouldn’t be surprised.)

>>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5)
>>> import datetime
>>> import arrow
>>> import pendulum
>>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 16]

回答 8

您可以使用gmtime

from time import gmtime

detailed_time = gmtime() 
#returns a struct_time object for current time

year = detailed_time.tm_year
month = detailed_time.tm_mon
day = detailed_time.tm_mday
hour = detailed_time.tm_hour
minute = detailed_time.tm_min

注意:可以将时间戳传递给gmtime,默认为time()返回的当前时间

eg.
gmtime(1521174681)

参见struct_time

You can use gmtime

from time import gmtime

detailed_time = gmtime() 
#returns a struct_time object for current time

year = detailed_time.tm_year
month = detailed_time.tm_mon
day = detailed_time.tm_mday
hour = detailed_time.tm_hour
minute = detailed_time.tm_min

Note: A time stamp can be passed to gmtime, default is current time as returned by time()

eg.
gmtime(1521174681)

See struct_time


回答 9

这是一个比较老的问题,但是我想出了一个我认为其他人可能会喜欢的解决方案。

def get_current_datetime_as_dict():
n = datetime.now()
t = n.timetuple()
field_names = ["year",
               "month",
               "day",
               "hour",
               "min",
               "sec",
               "weekday",
               "md",
               "yd"]
return dict(zip(field_names, t))

timetuple()可以与另一个数组一起压缩,这将创建带标签的元组。将其转换为字典,然后可以使用生成的产品get_current_datetime_as_dict()['year']

这比这里的其他一些解决方案有更多的开销,但是我发现能够在代码中为清楚起见而访问命名值真是太好了。

This is an older question, but I came up with a solution I thought others might like.

def get_current_datetime_as_dict():
n = datetime.now()
t = n.timetuple()
field_names = ["year",
               "month",
               "day",
               "hour",
               "min",
               "sec",
               "weekday",
               "md",
               "yd"]
return dict(zip(field_names, t))

timetuple() can be zipped with another array, which creates labeled tuples. Cast that to a dictionary and the resultant product can be consumed with get_current_datetime_as_dict()['year'].

This has a little more overhead than some of the other solutions on here, but I’ve found it’s so nice to be able to access named values for clartiy’s sake in the code.


回答 10

您可以使用datetime模块获取Python 2.7中的当前日期和时间

import datetime
print datetime.datetime.now()

输出:

2015-05-06 14:44:14.369392

you can use datetime module to get current Date and Time in Python 2.7

import datetime
print datetime.datetime.now()

Output :

2015-05-06 14:44:14.369392