标签归档:python-2.7

Python将项目添加到元组

问题:Python将项目添加到元组

我有一些object.ID-s,我尝试将其作为元组存储在用户会话中。当我添加第一个时,它可以工作,但是元组看起来像,(u'2',)但是当我尝试使用mytuple = mytuple + new.idgot error 添加新的时can only concatenate tuple (not "unicode") to tuple

I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like (u'2',) but when I try to add new one using mytuple = mytuple + new.id got error can only concatenate tuple (not "unicode") to tuple.


回答 0

您需要将第二个元素设为1元组,例如:

a = ('2',)
b = 'z'
new = a + (b,)

You need to make the second element a 1-tuple, eg:

a = ('2',)
b = 'z'
new = a + (b,)

回答 1

从Python 3.5(PEP 448)开始,您可以在元组,列表集和字典中进行解包:

a = ('2',)
b = 'z'
new = (*a, b)

Since Python 3.5 (PEP 448) you can do unpacking within a tuple, list set, and dict:

a = ('2',)
b = 'z'
new = (*a, b)

回答 2

从元组到列表再到元组:

a = ('2',)
b = 'b'

l = list(a)
l.append(b)

tuple(l)

或附有较长的项目清单

a = ('2',)
items = ['o', 'k', 'd', 'o']

l = list(a)

for x in items:
    l.append(x)

print tuple(l)

给你

>>> 
('2', 'o', 'k', 'd', 'o')

这里的重点是:列表是可变的序列类型。因此,您可以通过添加或删除元素来更改给定列表。元组是不可变的序列类型。您不能更改元组。因此,您必须创建一个新的

From tuple to list to tuple :

a = ('2',)
b = 'b'

l = list(a)
l.append(b)

tuple(l)

Or with a longer list of items to append

a = ('2',)
items = ['o', 'k', 'd', 'o']

l = list(a)

for x in items:
    l.append(x)

print tuple(l)

gives you

>>> 
('2', 'o', 'k', 'd', 'o')

The point here is: List is a mutable sequence type. So you can change a given list by adding or removing elements. Tuple is an immutable sequence type. You can’t change a tuple. So you have to create a new one.


回答 3

元组只能允许添加tuple到其中。最好的方法是:

mytuple =(u'2',)
mytuple +=(new.id,)

我使用以下数据尝试了相同的情况,但似乎一切正常。

>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')

Tuple can only allow adding tuple to it. The best way to do it is:

mytuple =(u'2',)
mytuple +=(new.id,)

I tried the same scenario with the below data it all seems to be working fine.

>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')

回答 4

>>> x = (u'2',)
>>> x += u"random string"

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", )  # concatenate a one-tuple instead
>>> x
(u'2', u'random string')
>>> x = (u'2',)
>>> x += u"random string"

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", )  # concatenate a one-tuple instead
>>> x
(u'2', u'random string')

回答 5

#1表格

a = ('x', 'y')
b = a + ('z',)
print(b)

#2表格

a = ('x', 'y')
b = a + tuple('b')
print(b)

#1 form

a = ('x', 'y')
b = a + ('z',)
print(b)

#2 form

a = ('x', 'y')
b = a + tuple('b')
print(b)

回答 6

最简单的说,添加到元组的最简单方法是用括号和逗号将要添加的元素括起来。

t = ('a', 4, 'string')
t = t + (5.0,)
print(t)

out: ('a', 4, 'string', 5.0)

Bottom line, the easiest way to append to a tuple is to enclose the element being added with parentheses and a comma.

t = ('a', 4, 'string')
t = t + (5.0,)
print(t)

out: ('a', 4, 'string', 5.0)

Pelican 3.3 pelican-quickstart错误“ ValueError:未知语言环境:UTF-8”

问题:Pelican 3.3 pelican-quickstart错误“ ValueError:未知语言环境:UTF-8”

当我尝试使用pelican3.3时,我键入了推荐的“ pelican-quickstart”,但出现了一些错误。

这些是错误:

(PelicanEnv)59-127-113-90:myblog Richo$ pelican-quickstart
Traceback (most recent call last):
  File "/Users/Richo/Dropbox/Github/PelicanEnv/bin/pelican-quickstart", line 9, in <module>
    load_entry_point('pelican==3.3', 'console_scripts', 'pelican-quickstart')()
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
    return ep.load()
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
    entry = __import__(self.module_name, globals(),globals(), ['__name__'])
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pelican/__init__.py", line 16, in <module>
    from pelican.generators import (ArticlesGenerator, PagesGenerator,
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pelican/generators.py", line 20, in <module>
    from pelican.readers import Readers
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pelican/readers.py", line 11, in <module>
    import docutils.core
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/docutils/core.py", line 20, in <module>
    from docutils import frontend, io, utils, readers, writers
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/docutils/frontend.py", line 41, in <module>
    import docutils.utils
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/docutils/utils/__init__.py", line 20, in <module>
    import docutils.io
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/docutils/io.py", line 18, in <module>
    from docutils.utils.error_reporting import locale_encoding, ErrorString, ErrorOutput
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/docutils/utils/error_reporting.py", line 47, in <module>
    locale_encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1]
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/locale.py", line 513, in getdefaultlocale
    return _parse_localename(localename)
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/locale.py", line 445, in _parse_localename
    raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8

我的操作系统是OS X Mavericks。

When I was trying to use pelican3.3, I typed the commend “pelican-quickstart”, some errors showed up.

These are the errors:

(PelicanEnv)59-127-113-90:myblog Richo$ pelican-quickstart
Traceback (most recent call last):
  File "/Users/Richo/Dropbox/Github/PelicanEnv/bin/pelican-quickstart", line 9, in <module>
    load_entry_point('pelican==3.3', 'console_scripts', 'pelican-quickstart')()
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pkg_resources.py", line 378, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pkg_resources.py", line 2566, in load_entry_point
    return ep.load()
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pkg_resources.py", line 2260, in load
    entry = __import__(self.module_name, globals(),globals(), ['__name__'])
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pelican/__init__.py", line 16, in <module>
    from pelican.generators import (ArticlesGenerator, PagesGenerator,
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pelican/generators.py", line 20, in <module>
    from pelican.readers import Readers
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/pelican/readers.py", line 11, in <module>
    import docutils.core
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/docutils/core.py", line 20, in <module>
    from docutils import frontend, io, utils, readers, writers
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/docutils/frontend.py", line 41, in <module>
    import docutils.utils
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/docutils/utils/__init__.py", line 20, in <module>
    import docutils.io
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/docutils/io.py", line 18, in <module>
    from docutils.utils.error_reporting import locale_encoding, ErrorString, ErrorOutput
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/site-packages/docutils/utils/error_reporting.py", line 47, in <module>
    locale_encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1]
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/locale.py", line 513, in getdefaultlocale
    return _parse_localename(localename)
  File "/Users/Richo/Dropbox/Github/PelicanEnv/lib/python2.7/locale.py", line 445, in _parse_localename
    raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8

My OS is OS X Mavericks.


回答 0

您可以尝试在此处此处发布的解决方案。基本上,向您的〜/ .bash_profile添加一些行:

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

有与此问题相关的未完成的错误报告。看来,Python对语言环境名称的格式做了一些假设,但这些假设并不是普遍有效的。显式设置这些环境变量基本上只是解决该错误的方法。

[编辑:]正如@asmeurer正确指出的那样,以上修正假定使用英语和美国。您应该从locale -a(由UTF-8)结尾的列表中选择您首选的语言环境。

You could try a solution posted here or here. Basically, add some lines to your ~/.bash_profile:

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

There is an outstanding bug report related to this issue. It appears that Python makes some assumptions about the format of locale names that aren’t universally valid. Explicitly setting these environment vars is basically just a workaround for that bug.

[Edit:] As @asmeurer correctly points out, the above fix assumes English and the U.S. You should really pick your preferred locale from the list given by locale -a (generally one that ends in UTF-8).


回答 1

Gerrat的答案有效,我相信我们应该提到,如果您使用诸如之类的东西zsh,则应在~/.zshrc~/.bash_profile或之前~/.bash_rc

Gerrat’s answer works, and I believe we should mention that if you use somthing like zsh, you should add lines to ~/.zshrc instead of ~/.bash_profile or ~/.bash_rc


回答 2

楼上的回答很快!但是我相信像我这样懒惰的人希望更改全局环境,以防万一更改为另一个登录用户后再也不会更改。所以我们需要像这样更改文件:

sudo vi /etc/profile or sudo vi /etc/bashrc

然后在以下文件中添加两行

export LC_ALL="en_US.UTF-8"
export LANG="en_US.UTF-8"

请记住,不要错过其中之一,它仅对$ LANG或$ LC_ALL不起作用。之后,运行命令以激活环境。

sudo source /etc/profile 
sudo source /etc/bashrc
source ~/.bash_profile 
source ~/.zshrc

同样,像我这样的懒惰人也可以在一行命令中完成。

echo -e "export LC_ALL=en_US.UTF-8\nexport LANG=en_US.UTF-8" >> ~/.bash_profile && source ~/.bash_profile

Upstairs answers were quick great! But I believe people lazy like me want to change the global environment in case never change again while change to another Login user. So we need to change the file like:

sudo vi /etc/profile or sudo vi /etc/bashrc

And then add the two line in the following files

export LC_ALL="en_US.UTF-8"
export LANG="en_US.UTF-8"

Remember do not miss one of them, it doesn’t work for me just $LANG or $LC_ALL. After that run the command to active the environment.

sudo source /etc/profile 
sudo source /etc/bashrc
source ~/.bash_profile 
source ~/.zshrc

Again, lazy people like me can finish in one line command.

echo -e "export LC_ALL=en_US.UTF-8\nexport LANG=en_US.UTF-8" >> ~/.bash_profile && source ~/.bash_profile

回答 3

我将在此处重新回答该问题,因为该问题被标记为该问题的重复,并且在许多方面,对此问题的公认答案是错误的。

这是OS X终端应用程序中的错误,仅在某些区域设置(国家/语言组合)中显示。在/ Applications / Utilities中打开终端,然后取消选中“在启动时设置区域设置环境变量”框。

这会将您的LANG环境变量设置为空。这可能会导致终端使用您的区域设置不正确。终端中的locale命令将告诉您使用了哪些设置。要使用正确的语言,请在您的bash个人资料中添加一行(通常是~/.profile

export LANG=your-lang

替换your-lang为您所用语言的正确语言环境说明符。该命令locale -a将显示所有说明符。例如,美国英语的语言代码为en_US.UTF-8。语言环境会影响可用时使用的翻译以及日期,货币和小数的格式。

请注意,此图片和内容摘自http://conda.pydata.org/docs/troubleshooting.html#unknown-locale(我也是该页面的原始作者)。

I’m reposting my answer from this question here, since that it was marked as a duplicate of this one, and the accepted answer on this question is wrong in many ways.

This is a bug in the OS X Terminal app that only shows up in certain locales (country/language combinations). Open Terminal in /Applications/Utilities and uncheck the box “Set locale environment variables on startup”.

This will set your LANG environment variable to be empty. This may cause terminal use to incorrect settings for your locale. The locale command in the Terminal will tell you what settings are used. To use the correct language, add a line to your bash profile (typically ~/.profile)

export LANG=your-lang

Replace your-lang with the correct locale specifier for your language. The command locale -a will show you all the specifiers. For example, the language code for US English is en_US.UTF-8. The locale affects what translations are used when they are available, and also how dates, currencies, and decimals are formatted.

Note, this image and content were taken from http://conda.pydata.org/docs/troubleshooting.html#unknown-locale (I’m also the original author of that page).


回答 4

此处提到的解决方案都无法在本地应用引擎环境中运行python 3.7项目。

虽然我可以通过命令行检索语言环境,但是:

python3 -c 'import locale; print(locale.getdefaultlocale());'
('en_US', 'UTF-8')  

在应用程序引擎环境中找不到该语言环境:

File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/locale.py", line 568, in getdefaultlocale
    return _parse_localename(localename)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/locale.py", line 495, in _parse_localename
    raise ValueError('unknown locale: %s' % localename)
ValueError: unknown locale: UTF-8

所以,我必须明确地设定env_variables在我的app.yaml文件:

env_variables:
  LC_ALL: "en_US:UTF_8"
  LC_CTYPE: "en_US:UTF_8"

这样就解决了该错误。

None of the solutions mentioned here worked for me running a python 3.7 project in a local app engine environment.

Although I could retrieve the locale through the command line just fine:

python3 -c 'import locale; print(locale.getdefaultlocale());'
('en_US', 'UTF-8')  

That locale could not be found within the app engine environment:

File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/locale.py", line 568, in getdefaultlocale
    return _parse_localename(localename)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/locale.py", line 495, in _parse_localename
    raise ValueError('unknown locale: %s' % localename)
ValueError: unknown locale: UTF-8

So I had to explicitly set env_variables in my app.yaml file:

env_variables:
  LC_ALL: "en_US:UTF_8"
  LC_CTYPE: "en_US:UTF_8"

And that solved the bug.


回答 5

由于某些原因,我还需要:

export LC_CTYPE=en_US.UTF-8

For some reason I also needed:

export LC_CTYPE=en_US.UTF-8

AttributeError:“ datetime”模块没有属性“ strptime”

问题:AttributeError:“ datetime”模块没有属性“ strptime”

这是我的Transaction课:

class Transaction(object):
    def __init__(self, company, num, price, date, is_buy):
        self.company = company
        self.num = num
        self.price = price
        self.date = datetime.strptime(date, "%Y-%m-%d")
        self.is_buy = is_buy

当我尝试运行该date功能时:

tr = Transaction('AAPL', 600, '2013-10-25')
print tr.date

我收到以下错误:

   self.date = datetime.strptime(self.d, "%Y-%m-%d")
 AttributeError: 'module' object has no attribute 'strptime'

我该如何解决?

Here is my Transaction class:

class Transaction(object):
    def __init__(self, company, num, price, date, is_buy):
        self.company = company
        self.num = num
        self.price = price
        self.date = datetime.strptime(date, "%Y-%m-%d")
        self.is_buy = is_buy

And when I’m trying to run the date function:

tr = Transaction('AAPL', 600, '2013-10-25')
print tr.date

I’m getting the following error:

   self.date = datetime.strptime(self.d, "%Y-%m-%d")
 AttributeError: 'module' object has no attribute 'strptime'

How can I fix that?


回答 0

如果我不得不猜测,您这样做:

import datetime

在代码的顶部。这意味着您必须执行以下操作:

datetime.datetime.strptime(date, "%Y-%m-%d")

访问该strptime方法。或者,您可以将import语句更改为此:

from datetime import datetime

并按原样访问它。

制作该datetime模块的人员还命名了他们的Classdatetime

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

回答 1

使用正确的调用:strptime是类的datetime.datetime类方法,不是datetime模块中的函数。

self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")

正如乔恩·克莱门茨(Jon Clements)在评论中提到的那样,有人这样做了from datetime import datetime,这会将datetime名称绑定到datetime类上,并使您的初始代码正常工作。

要确定您将来遇到的情况,请查看导入语句

  • import datetime:这就是模块(这就是您现在所拥有的)。
  • from datetime import datetime:那是类。

Use the correct call: strptime is a classmethod of the datetime.datetime class, it’s not a function in the datetime module.

self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")

As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.

To identify which case you’re facing (in the future), look at your import statements

  • import datetime: that’s the module (that’s what you have right now).
  • from datetime import datetime: that’s the class.

回答 2

我遇到了同样的问题,这不是您告诉的解决方案。因此,我将“从datetime导入datetime”更改为“ import datetime”。之后,借助“ datetime.datetime”,我可以正确获取整个模块。我想这是对该问题的正确答案。

I got the same problem and it is not the solution that you told. So I changed the “from datetime import datetime” to “import datetime”. After that with the help of “datetime.datetime” I can get the whole modules correctly. I guess this is the correct answer to that question.


向后移植将Python 3 open(encoding =“ utf-8”)移植到Python 2

问题:向后移植将Python 3 open(encoding =“ utf-8”)移植到Python 2

我有一个为Python 3构建的Python代码库,它使用带有编码参数的Python 3样式的open():

https://github.com/miohtama/vvv/blob/master/vvv/textlineplugin.py#L47

    with open(fname, "rt", encoding="utf-8") as f:

现在,我想将此代码反向移植到Python 2.x,这样我将拥有一个可用于Python 2和Python 3的代码库。

建议的解决方法是什么 open()差异和缺乏编码参数的什么?

我可以使用Python 3 open()样式的文件处理程序来流字节字符串,以便像Python 2那样工作open()吗?

I have a Python codebase, built for Python 3, which uses Python 3 style open() with encoding parameter:

https://github.com/miohtama/vvv/blob/master/vvv/textlineplugin.py#L47

    with open(fname, "rt", encoding="utf-8") as f:

Now I’d like to backport this code to Python 2.x, so that I would have a codebase which works with Python 2 and Python 3.

What’s the recommended strategy to work around open() differences and lack of encoding parameter?

Could I have a Python 3 open() style file handler which streams bytestrings, so it would act like Python 2 open()?


回答 0

1.在Python 2中获取编码参数:

如果您只需要支持Python 2.6和2.7,则可以使用io.open代替openio是Python 3的新io子系统,它也存在于Python 2,6 ans 2.7中。请注意,在Python 2.6(以及3.0)中,它是完全在python中实现的,并且运行速度非常慢,因此,如果您需要快速读取文件,则不是一个好的选择。

如果需要速度,并且需要支持Python 2.6或更早版本,则可以codecs.open改用。它也有一个编码参数,io.open除了它以不同的方式处理行尾之外,它与之非常相似。

2.要获取open()可流字节串的Python 3 样式文件处理程序,请执行以下操作:

open(filename, 'rb')

注意“ b”,意思是“二进制”。

1. To get an encoding parameter in Python 2:

If you only need to support Python 2.6 and 2.7 you can use io.open instead of open. io is the new io subsystem for Python 3, and it exists in Python 2,6 ans 2.7 as well. Please be aware that in Python 2.6 (as well as 3.0) it’s implemented purely in python and very slow, so if you need speed in reading files, it’s not a good option.

If you need speed, and you need to support Python 2.6 or earlier, you can use codecs.open instead. It also has an encoding parameter, and is quite similar to io.open except it handles line-endings differently.

2. To get a Python 3 open() style file handler which streams bytestrings:

open(filename, 'rb')

Note the ‘b’, meaning ‘binary’.


回答 1

我认为

from io import open

应该做。

I think

from io import open

should do.


回答 2

这是一种方法:

with open("filename.txt", "rb") as f:
    contents = f.read().decode("UTF-8")

Here’s one way:

with open("filename.txt", "rb") as f:
    contents = f.read().decode("UTF-8")

回答 3

这可能会达到目的:

import sys
if sys.version_info[0] > 2:
    # py3k
    pass
else:
    # py2
    import codecs
    import warnings
    def open(file, mode='r', buffering=-1, encoding=None,
             errors=None, newline=None, closefd=True, opener=None):
        if newline is not None:
            warnings.warn('newline is not supported in py2')
        if not closefd:
            warnings.warn('closefd is not supported in py2')
        if opener is not None:
            warnings.warn('opener is not supported in py2')
        return codecs.open(filename=file, mode=mode, encoding=encoding,
                    errors=errors, buffering=buffering)

然后,您可以使用python3方式保留代码。

请注意,一些API一样newlineclosefdopener不工作

This may do the trick:

import sys
if sys.version_info[0] > 2:
    # py3k
    pass
else:
    # py2
    import codecs
    import warnings
    def open(file, mode='r', buffering=-1, encoding=None,
             errors=None, newline=None, closefd=True, opener=None):
        if newline is not None:
            warnings.warn('newline is not supported in py2')
        if not closefd:
            warnings.warn('closefd is not supported in py2')
        if opener is not None:
            warnings.warn('opener is not supported in py2')
        return codecs.open(filename=file, mode=mode, encoding=encoding,
                    errors=errors, buffering=buffering)

Then you can keep you code in the python3 way.

Note that some APIs like newline, closefd, opener do not work


回答 4

如果您使用six,则可以尝试使用最新的Python 3 API并可以在Python 2/3中运行:

import six

if six.PY2:
    # FileNotFoundError is only available since Python 3.3
    FileNotFoundError = IOError
    from io import open

fname = 'index.rst'
try:
    with open(fname, "rt", encoding="utf-8") as f:
        pass
        # do_something_with_f ...
except FileNotFoundError:
    print('Oops.')

而且,放弃Python 2支持只是删除与相关的所有内容six

If you are using six, you can try this, by which utilizing the latest Python 3 API and can run in both Python 2/3:

import six

if six.PY2:
    # FileNotFoundError is only available since Python 3.3
    FileNotFoundError = IOError
    from io import open

fname = 'index.rst'
try:
    with open(fname, "rt", encoding="utf-8") as f:
        pass
        # do_something_with_f ...
except FileNotFoundError:
    print('Oops.')

And, Python 2 support abandon is just deleting everything related to six.


Python中的邮政编码列表

问题:Python中的邮政编码列表

我正在尝试学习如何“压缩”列表。为此,我有一个程序,在某个特定位置执行以下操作:

x1, x2, x3 = stuff.calculations(withdataa)

这给了我三个列表,x1x2,和x3,每一个,比方说,大小为20。

现在,我这样做:

zipall = zip(x1, x2, x3)

但是,当我这样做时:

print "len of zipall %s" % len(zipall)

我得到20,这不是我期望的。我预计三个。我认为我做的事情根本上是错误的。

I am trying to learn how to “zip” lists. To this end, I have a program, where at a particular point, I do the following:

x1, x2, x3 = stuff.calculations(withdataa)

This gives me three lists, x1, x2, and x3, each of, say, size 20.

Now, I do:

zipall = zip(x1, x2, x3)

However, when I do:

print "len of zipall %s" % len(zipall)

I get 20, which is not what I expected. I expected three. I think I am doing something fundamentally wrong.


回答 0

zip()三个包含20个元素的列表放在一起时,结果将包含20个元素。每个元素都是一个三元组。

你自己看:

In [1]: a = b = c = range(20)

In [2]: zip(a, b, c)
Out[2]: 
[(0, 0, 0),
 (1, 1, 1),
 ...
 (17, 17, 17),
 (18, 18, 18),
 (19, 19, 19)]

要找出每个元组包含多少个元素,可以检查第一个元素的长度:

In [3]: result = zip(a, b, c)

In [4]: len(result[0])
Out[4]: 3

当然,如果列表开头是空的,这将不起作用。

When you zip() together three lists containing 20 elements each, the result has twenty elements. Each element is a three-tuple.

See for yourself:

In [1]: a = b = c = range(20)

In [2]: zip(a, b, c)
Out[2]: 
[(0, 0, 0),
 (1, 1, 1),
 ...
 (17, 17, 17),
 (18, 18, 18),
 (19, 19, 19)]

To find out how many elements each tuple contains, you could examine the length of the first element:

In [3]: result = zip(a, b, c)

In [4]: len(result[0])
Out[4]: 3

Of course, this won’t work if the lists were empty to start with.


回答 1

zip 需要一堆喜欢的清单

a: a1 a2 a3 a4 a5 a6 a7...
b: b1 b2 b3 b4 b5 b6 b7...
c: c1 c2 c3 c4 c5 c6 c7...

并将它们“压缩”到一个列表,其条目为3元组(ai, bi, ci)。想象一下从左到右水平绘制一个拉链。

zip takes a bunch of lists likes

a: a1 a2 a3 a4 a5 a6 a7...
b: b1 b2 b3 b4 b5 b6 b7...
c: c1 c2 c3 c4 c5 c6 c7...

and “zips” them into one list whose entries are 3-tuples (ai, bi, ci). Imagine drawing a zipper horizontally from left to right.


回答 2

在Python 2.7中,这可能工作得很好:

>>> a = b = c = range(20)
>>> zip(a, b, c)

但是在Python 3.4中应该是这样(否则结果将类似于<zip object at 0x00000256124E7DC8>):

>>> a = b = c = range(20)
>>> list(zip(a, b, c))

In Python 2.7 this might have worked fine:

>>> a = b = c = range(20)
>>> zip(a, b, c)

But in Python 3.4 it should be (otherwise, the result will be something like <zip object at 0x00000256124E7DC8>):

>>> a = b = c = range(20)
>>> list(zip(a, b, c))

回答 3

zip 创建一个新列表,其中填充了包含可迭代参数元素的元组:

>>> zip ([1,2],[3,4])
[(1,3), (2,4)]

我希望您能尝试创建一个元组,其中每个元素都是一个列表。

zip creates a new list, filled with tuples containing elements from the iterable arguments:

>>> zip ([1,2],[3,4])
[(1,3), (2,4)]

I expect what you try to so is create a tuple where each element is a list.


回答 4

资料来源:我的博客文章(更好的格式)

numbers = [1,2,3]
letters = 'abcd'

zip(numbers, letters)
# [(1, 'a'), (2, 'b'), (3, 'c')]

输入项

零个或多个可迭代项[1](例如列表,字符串,元组,字典)

输出(列表)

第一个元组=(数字的element_1,字母的element_1)

第二个元组=(e_2个数字,e_2个字母)

第n个元组=(e_n个数字,e_n个字母)

  1. n个元组的列表:n是最短参数(输入)的长度
    • len(数字)== 3 <len(字母)== 4→短= 3→返回3个元组
  2. 每个元组的长度= args的数量(元组从每个arg中获取一个元素)
    • args =(数字,字母); len(args)== 2→具有2个元素的元组
  3. i第元组=(element_i arg1,element_i arg2…,element_i arg n

边缘案例

1)空字符串:len(str)= 0 =无元组

2)单个字符串:len(str)== 2个元组,len(args)== 1个元素

zip()
# []
zip('')
# []
zip('hi')
# [('h',), ('i',)]

压缩中!

1.从两个列表中构建字典[2]

keys = ["drink","band","food"]
values = ["La Croix", "Daft Punk", "Sushi"]

my_favorite = dict( zip(keys, values) )

my_favorite["drink"]
# 'La Croix'

my_faves = dict()
for i in range(len(keys)):
    my_faves[keys[i]] = values[i]
  • zip 是一种优雅,清晰,简洁的解决方案

2.打印表格中的列

“ *” [3]称为“拆箱”: f(*[arg1,arg2,arg3]) == f(arg1, arg2, arg3)

student_grades = [
[   'Morty'  ,  1   ,  "B"  ],
[   'Rick'   ,  4   ,  "A"  ],
[   'Jerry'  ,  3   ,  "M"  ],
[  'Kramer'  ,  0   ,  "F"  ],
]

row_1 = student_grades[0]
print row_1
# ['Morty', 1, 'B']

columns = zip(*student_grades)
names = columns[0]
print names
# ('Morty', 'Rick', 'Jerry', 'Kramer')

额外信用:解压缩

zip(*args) 之所以称为“解压缩”,是因为它具有相反的作用 zip

numbers = (1,2,3)
letters = ('a','b','c')

zipped = zip(numbers, letters)
print zipped
# [(1, 'a'), (2, 'b'), (3, 'c')]

unzipped = zip(*zipped)
print unzipped
# [(1, 2, 3), ('a', 'b', 'c')]
  • unzipped:tuple_1 =每个压缩元组的e1。元组_2 =每个e2zipped

脚注

  1. 一个能够一次返回其成员的对象(例如列表[1,2,3],字符串“ I like codin”,元组(1,2,3),字典{‘a’:1,’b’ :2})
  2. {key1:value1,key2:value2 …}
  3. “拆箱”(*)

* 码:

# foo - function, returns sum of two arguments
def foo(x,y):
    return x + y
print foo(3,4)
# 7

numbers = [1,2]
print foo(numbers)
# TypeError: foo() takes exactly 2 arguments (1 given)

print foo(*numbers)
# 3

*拿了numbers(1个参数)并将其2个元素“拆包”为2个参数

Source: My Blog Post (better formatting)

Example

numbers = [1,2,3]
letters = 'abcd'

zip(numbers, letters)
# [(1, 'a'), (2, 'b'), (3, 'c')]

Input

Zero or more iterables [1] (ex. list, string, tuple, dictionary)

Output (list)

1st tuple = (element_1 of numbers, element_1 of letters)

2nd tuple = (e_2 numbers, e_2 letters)

n-th tuple = (e_n numbers, e_n letters)

  1. List of n tuples: n is the length of the shortest argument (input)
    • len(numbers) == 3 < len(letters) == 4 → short= 3 → return 3 tuples
  2. Length each tuple = # of args (tuple takes an element from each arg)
    • args = (numbers,letters); len(args) == 2 → tuple with 2 elements
  3. ith tuple = (element_i arg1, element_i arg2…, element_i argn)

Edge Cases

1) Empty String: len(str)= 0 = no tuples

2) Single String: len(str) == 2 tuples with len(args) == 1 element(s)

zip()
# []
zip('')
# []
zip('hi')
# [('h',), ('i',)]

Zip in Action!

1. Build a dictionary [2] out of two lists

keys = ["drink","band","food"]
values = ["La Croix", "Daft Punk", "Sushi"]

my_favorite = dict( zip(keys, values) )

my_favorite["drink"]
# 'La Croix'

my_faves = dict()
for i in range(len(keys)):
    my_faves[keys[i]] = values[i]
  • zip is an elegant, clear, & concise solution

2. Print columns in a table

“*” [3] is called “unpacking”: f(*[arg1,arg2,arg3]) == f(arg1, arg2, arg3)

student_grades = [
[   'Morty'  ,  1   ,  "B"  ],
[   'Rick'   ,  4   ,  "A"  ],
[   'Jerry'  ,  3   ,  "M"  ],
[  'Kramer'  ,  0   ,  "F"  ],
]

row_1 = student_grades[0]
print row_1
# ['Morty', 1, 'B']

columns = zip(*student_grades)
names = columns[0]
print names
# ('Morty', 'Rick', 'Jerry', 'Kramer')

Extra Credit: Unzipping

zip(*args) is called “unzipping” because it has the inverse effect of zip

numbers = (1,2,3)
letters = ('a','b','c')

zipped = zip(numbers, letters)
print zipped
# [(1, 'a'), (2, 'b'), (3, 'c')]

unzipped = zip(*zipped)
print unzipped
# [(1, 2, 3), ('a', 'b', 'c')]
  • unzipped: tuple_1 = e1 of each zipped tuple. tuple_2 = e2 of each zipped

Footnotes

  1. An object capable of returning its members one at a time (ex. list [1,2,3], string ‘I like codin’, tuple (1,2,3), dictionary {‘a’:1, ‘b’:2})
  2. {key1:value1, key2:value2…}
  3. “Unpacking” (*)

* Code:

# foo - function, returns sum of two arguments
def foo(x,y):
    return x + y
print foo(3,4)
# 7

numbers = [1,2]
print foo(numbers)
# TypeError: foo() takes exactly 2 arguments (1 given)

print foo(*numbers)
# 3

* took numbers (1 arg) and “unpacked” its’ 2 elements into 2 args


回答 5

基本上,zip函数适用于Python中的列表,元组和字典。如果您使用的是IPython,则只需键入zip?并检查zip()是关于什么的。

如果您不使用IPython,则只需安装即可:“ pip install ipython”

对于列表

a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)

输出是 [('a', 'p'), ('b', 'q'), ('c', 'r')

对于字典:

c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)

输出为:

[('gaurav', 'amit'),
 ('nilesh', 'swapnil'),
 ('ramesh', 'anish'),
 ('anu', 'raghu')]

Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.

If you are not using IPython then just install it: “pip install ipython”

For lists

a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)

The output is [('a', 'p'), ('b', 'q'), ('c', 'r')

For dictionary:

c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)

The output is:

[('gaurav', 'amit'),
 ('nilesh', 'swapnil'),
 ('ramesh', 'anish'),
 ('anu', 'raghu')]

回答 6

Python 3中,它 zip返回一个迭代器,并且需要传递给列表函数以获取压缩的元组:

x = [1, 2, 3]; y = ['a','b','c']
z = zip(x, y)
z = list(z)
print(z)
>>> [(1, 'a'), (2, 'b'), (3, 'c')]

然后unzip返回给他们,只需将压缩的迭代器进行共轭即可:

x_back, y_back = zip(*z)
print(x_back); print(y_back)
>>> (1, 2, 3)
>>> ('a', 'b', 'c')

如果需要列表的原始形式而不是元组:

x_back, y_back = zip(*z)
print(list(x_back)); print(list(y_back))
>>> [1,2,3]
>>> ['a','b','c']

In Python 3 zip returns an iterator instead and needs to be passed to a list function to get the zipped tuples:

x = [1, 2, 3]; y = ['a','b','c']
z = zip(x, y)
z = list(z)
print(z)
>>> [(1, 'a'), (2, 'b'), (3, 'c')]

Then to unzip them back just conjugate the zipped iterator:

x_back, y_back = zip(*z)
print(x_back); print(y_back)
>>> (1, 2, 3)
>>> ('a', 'b', 'c')

If the original form of list is needed instead of tuples:

x_back, y_back = zip(*z)
print(list(x_back)); print(list(y_back))
>>> [1,2,3]
>>> ['a','b','c']

回答 7

为了完整起见。

当压缩列表的长度不相等时。结果列表的长度将成为最短的长度,而不会发生任何错误

>>> a = [1]
>>> b = ["2", 3]
>>> zip(a,b)
[(1, '2')]

For the completeness’s sake.

When zipped lists’ lengths are not equal. The result list’s length will become the shortest one without any error occurred

>>> a = [1]
>>> b = ["2", 3]
>>> zip(a,b)
[(1, '2')]

回答 8

我不认为会zip返回列表。zip返回一个生成器。您必须要做的list(zip(a, b))是获取元组列表。

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
list(zipped)

I don’t think zip returns a list. zip returns a generator. You have got to do list(zip(a, b)) to get a list of tuples.

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
list(zipped)

回答 9

值得在这里添加,因为它是zip中一个如此高度排名的问题。zip很棒,惯用的Python-但是对于大型列表而言,它的伸缩性根本不好。

代替:

books = ['AAAAAAA', 'BAAAAAAA', ... , 'ZZZZZZZ']
words = [345, 567, ... , 672]

for book, word in zip(books, words):
   print('{}: {}'.format(book, word))

izip。对于现代处理,它将其存储在L1高速缓存中,对于较大的列表,它的性能要好得多。使用它就像添加一个i

for book, word in izip(books, words):
   print('{}: {}'.format(book, word))

It’s worth adding here as it is such a highly ranking question on zip. zip is great, idiomatic Python – but it doesn’t scale very well at all for large lists.

Instead of:

books = ['AAAAAAA', 'BAAAAAAA', ... , 'ZZZZZZZ']
words = [345, 567, ... , 672]

for book, word in zip(books, words):
   print('{}: {}'.format(book, word))

Use izip. For modern processing, it stores it in L1 Cache memory and is far more performant for larger lists. Use it as simply as adding an i:

for book, word in izip(books, words):
   print('{}: {}'.format(book, word))

如何在Python中创建嵌套字典?

问题:如何在Python中创建嵌套字典?

我有2个CSV文件:“数据”和“映射”:

  • ‘映射’文件有4列:Device_NameGDNDevice_Type,和Device_OS。填充所有四个列。
  • “数据”文件具有这些相同的列,其中Device_Name填充了列,而其他三列为空白。
  • 我希望我的Python代码来打开这两个文件并为每个Device_Name数据文件,它的映射GDNDevice_Type以及Device_OS从映射文件中值。

我知道只有2列存在时才需要使用dict(需要映射1列),但是当需要映射3列时我不知道如何实现。

以下是我尝试完成的映射的代码Device_Type

x = dict([])
with open("Pricing Mapping_2013-04-22.csv", "rb") as in_file1:
    file_map = csv.reader(in_file1, delimiter=',')
    for row in file_map:
       typemap = [row[0],row[2]]
       x.append(typemap)

with open("Pricing_Updated_Cleaned.csv", "rb") as in_file2, open("Data Scraper_GDN.csv", "wb") as out_file:
    writer = csv.writer(out_file, delimiter=',')
    for row in csv.reader(in_file2, delimiter=','):
         try:
              row[27] = x[row[11]]
         except KeyError:
              row[27] = ""
         writer.writerow(row)

它返回Attribute Error

经过研究后,我认为我需要创建一个嵌套的字典,但是我不知道如何执行此操作。

I have 2 CSV files: ‘Data’ and ‘Mapping’:

  • ‘Mapping’ file has 4 columns: Device_Name, GDN, Device_Type, and Device_OS. All four columns are populated.
  • ‘Data’ file has these same columns, with Device_Name column populated and the other three columns blank.
  • I want my Python code to open both files and for each Device_Name in the Data file, map its GDN, Device_Type, and Device_OS value from the Mapping file.

I know how to use dict when only 2 columns are present (1 is needed to be mapped) but I don’t know how to accomplish this when 3 columns need to be mapped.

Following is the code using which I tried to accomplish mapping of Device_Type:

x = dict([])
with open("Pricing Mapping_2013-04-22.csv", "rb") as in_file1:
    file_map = csv.reader(in_file1, delimiter=',')
    for row in file_map:
       typemap = [row[0],row[2]]
       x.append(typemap)

with open("Pricing_Updated_Cleaned.csv", "rb") as in_file2, open("Data Scraper_GDN.csv", "wb") as out_file:
    writer = csv.writer(out_file, delimiter=',')
    for row in csv.reader(in_file2, delimiter=','):
         try:
              row[27] = x[row[11]]
         except KeyError:
              row[27] = ""
         writer.writerow(row)

It returns Attribute Error.

After some researching, I think I need to create a nested dict, but I don’t have any idea how to do this.


回答 0

嵌套字典是字典中的字典。非常简单的事情。

>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d
{'dict1': {'innerkey': 'value'}}

你也可以使用一个defaultdictcollections包装,以方便创建嵌套的字典。

>>> import collections
>>> d = collections.defaultdict(dict)
>>> d['dict1']['innerkey'] = 'value'
>>> d  # currently a defaultdict type
defaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})
>>> dict(d)  # but is exactly like a normal dictionary.
{'dict1': {'innerkey': 'value'}}

您可以根据需要填充。

我建议在你的代码的东西下面:

d = {}  # can use defaultdict(dict) instead

for row in file_map:
    # derive row key from something 
    # when using defaultdict, we can skip the next step creating a dictionary on row_key
    d[row_key] = {} 
    for idx, col in enumerate(row):
        d[row_key][idx] = col

根据您的评论

可能上面的代码令人困惑。我的问题简而言之:我有2个文件a.csv b.csv,a.csv有4列ijkl,b.csv也有这些列。我是这些csv的关键列。jkl列在a.csv中为空,但在b.csv中填充。我想使用’i’作为键列将b.csv中的jk l列的值映射到a.csv文件

我的建议是什么这样(不使用defaultdict):

a_file = "path/to/a.csv"
b_file = "path/to/b.csv"

# read from file a.csv
with open(a_file) as f:
    # skip headers
    f.next()
    # get first colum as keys
    keys = (line.split(',')[0] for line in f) 

# create empty dictionary:
d = {}

# read from file b.csv
with open(b_file) as f:
    # gather headers except first key header
    headers = f.next().split(',')[1:]
    # iterate lines
    for line in f:
        # gather the colums
        cols = line.strip().split(',')
        # check to make sure this key should be mapped.
        if cols[0] not in keys:
            continue
        # add key to dict
        d[cols[0]] = dict(
            # inner keys are the header names, values are columns
            (headers[idx], v) for idx, v in enumerate(cols[1:]))

但是请注意,用于解析csv文件的是csv模块

A nested dict is a dictionary within a dictionary. A very simple thing.

>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d
{'dict1': {'innerkey': 'value'}}

You can also use a defaultdict from the collections package to facilitate creating nested dictionaries.

>>> import collections
>>> d = collections.defaultdict(dict)
>>> d['dict1']['innerkey'] = 'value'
>>> d  # currently a defaultdict type
defaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})
>>> dict(d)  # but is exactly like a normal dictionary.
{'dict1': {'innerkey': 'value'}}

You can populate that however you want.

I would recommend in your code something like the following:

d = {}  # can use defaultdict(dict) instead

for row in file_map:
    # derive row key from something 
    # when using defaultdict, we can skip the next step creating a dictionary on row_key
    d[row_key] = {} 
    for idx, col in enumerate(row):
        d[row_key][idx] = col

According to your comment:

may be above code is confusing the question. My problem in nutshell: I have 2 files a.csv b.csv, a.csv has 4 columns i j k l, b.csv also has these columns. i is kind of key columns for these csvs’. j k l column is empty in a.csv but populated in b.csv. I want to map values of j k l columns using ‘i` as key column from b.csv to a.csv file

My suggestion would be something like this (without using defaultdict):

a_file = "path/to/a.csv"
b_file = "path/to/b.csv"

# read from file a.csv
with open(a_file) as f:
    # skip headers
    f.next()
    # get first colum as keys
    keys = (line.split(',')[0] for line in f) 

# create empty dictionary:
d = {}

# read from file b.csv
with open(b_file) as f:
    # gather headers except first key header
    headers = f.next().split(',')[1:]
    # iterate lines
    for line in f:
        # gather the colums
        cols = line.strip().split(',')
        # check to make sure this key should be mapped.
        if cols[0] not in keys:
            continue
        # add key to dict
        d[cols[0]] = dict(
            # inner keys are the header names, values are columns
            (headers[idx], v) for idx, v in enumerate(cols[1:]))

Please note though, that for parsing csv files there is a csv module.


回答 1

更新:对于嵌套字典的任意长度,请转到此答案

使用集合中的defaultdict函数。

高性能:当数据集很大时,“ if key not in dict”非常昂贵。

维护成本低:使代码更具可读性,并且可以轻松扩展。

from collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val

UPDATE: For an arbitrary length of a nested dictionary, go to this answer.

Use the defaultdict function from the collections.

High performance: “if key not in dict” is very expensive when the data set is large.

Low maintenance: make the code more readable and can be easily extended.

from collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val

回答 2

对于任意级别的嵌套:

In [2]: def nested_dict():
   ...:     return collections.defaultdict(nested_dict)
   ...:

In [3]: a = nested_dict()

In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})

In [5]: a['a']['b']['c'] = 1

In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
            {'a': defaultdict(<function __main__.nested_dict>,
                         {'b': defaultdict(<function __main__.nested_dict>,
                                      {'c': 1})})})

For arbitrary levels of nestedness:

In [2]: def nested_dict():
   ...:     return collections.defaultdict(nested_dict)
   ...:

In [3]: a = nested_dict()

In [4]: a
Out[4]: defaultdict(<function __main__.nested_dict>, {})

In [5]: a['a']['b']['c'] = 1

In [6]: a
Out[6]:
defaultdict(<function __main__.nested_dict>,
            {'a': defaultdict(<function __main__.nested_dict>,
                         {'b': defaultdict(<function __main__.nested_dict>,
                                      {'c': 1})})})

回答 3

重要的是要记住,在使用defaultdict和类似的嵌套dict模块(如nested_dict)时,查找不存在的键可能会无意间在dict中创建新的键条目,并造成很多破坏。

这是带有nested_dict模块的Python3示例:

import nested_dict as nd
nest = nd.nested_dict()
nest['outer1']['inner1'] = 'v11'
nest['outer1']['inner2'] = 'v12'
print('original nested dict: \n', nest)
try:
    nest['outer1']['wrong_key1']
except KeyError as e:
    print('exception missing key', e)
print('nested dict after lookup with missing key.  no exception raised:\n', nest)

# Instead, convert back to normal dict...
nest_d = nest.to_dict(nest)
try:
    print('converted to normal dict. Trying to lookup Wrong_key2')
    nest_d['outer1']['wrong_key2']
except KeyError as e:
    print('exception missing key', e)
else:
    print(' no exception raised:\n')

# ...or use dict.keys to check if key in nested dict
print('checking with dict.keys')
print(list(nest['outer1'].keys()))
if 'wrong_key3' in list(nest.keys()):

    print('found wrong_key3')
else:
    print(' did not find wrong_key3')

输出为:

original nested dict:   {"outer1": {"inner2": "v12", "inner1": "v11"}}

nested dict after lookup with missing key.  no exception raised:  
{"outer1": {"wrong_key1": {}, "inner2": "v12", "inner1": "v11"}} 

converted to normal dict. 
Trying to lookup Wrong_key2 

exception missing key 'wrong_key2' 

checking with dict.keys 

['wrong_key1', 'inner2', 'inner1']  
did not find wrong_key3

It is important to remember when using defaultdict and similar nested dict modules such as nested_dict, that looking up a nonexistent key may inadvertently create a new key entry in the dict and cause a lot of havoc.

Here is a Python3 example with nested_dict module:

import nested_dict as nd
nest = nd.nested_dict()
nest['outer1']['inner1'] = 'v11'
nest['outer1']['inner2'] = 'v12'
print('original nested dict: \n', nest)
try:
    nest['outer1']['wrong_key1']
except KeyError as e:
    print('exception missing key', e)
print('nested dict after lookup with missing key.  no exception raised:\n', nest)

# Instead, convert back to normal dict...
nest_d = nest.to_dict(nest)
try:
    print('converted to normal dict. Trying to lookup Wrong_key2')
    nest_d['outer1']['wrong_key2']
except KeyError as e:
    print('exception missing key', e)
else:
    print(' no exception raised:\n')

# ...or use dict.keys to check if key in nested dict
print('checking with dict.keys')
print(list(nest['outer1'].keys()))
if 'wrong_key3' in list(nest.keys()):

    print('found wrong_key3')
else:
    print(' did not find wrong_key3')

Output is:

original nested dict:   {"outer1": {"inner2": "v12", "inner1": "v11"}}

nested dict after lookup with missing key.  no exception raised:  
{"outer1": {"wrong_key1": {}, "inner2": "v12", "inner1": "v11"}} 

converted to normal dict. 
Trying to lookup Wrong_key2 

exception missing key 'wrong_key2' 

checking with dict.keys 

['wrong_key1', 'inner2', 'inner1']  
did not find wrong_key3

运行`pip install`的Ubuntu给出错误’无法构建以下必需的软件包:* freetype’

问题:运行`pip install`的Ubuntu给出错误’无法构建以下必需的软件包:* freetype’

执行时pip install -r requirements.txt,在安装阶段出现以下错误matplotlib

REQUIRED DEPENDENCIES AND EXTENSIONS
                 numpy: yes [not found. pip may install it below.]
              dateutil: yes [dateutil was not found. It is required for date
                        axis support. pip/easy_install may attempt to
                        install it after matplotlib.]
               tornado: yes [tornado was not found. It is required for the
                        WebAgg backend. pip/easy_install may attempt to
                        install it after matplotlib.]
             pyparsing: yes [pyparsing was not found. It is required for
                        mathtext support. pip/easy_install may attempt to
                        install it after matplotlib.]
                 pycxx: yes [Couldn't import.  Using local copy.]
                libagg: yes [pkg-config information for 'libagg' could not
                        be found. Using local copy.]
              freetype: no  [pkg-config information for 'freetype2' could
                        not be found.]

The following required packages can not be built:

                    * freetype

还不应该pip install -r requirements.txt安装freetype吗?freetype应该如何在Ubuntu 12.04中安装以便与它一起使用matplotlib

When performing pip install -r requirements.txt, I get the following error during the stage where it is installing matplotlib:

REQUIRED DEPENDENCIES AND EXTENSIONS
                 numpy: yes [not found. pip may install it below.]
              dateutil: yes [dateutil was not found. It is required for date
                        axis support. pip/easy_install may attempt to
                        install it after matplotlib.]
               tornado: yes [tornado was not found. It is required for the
                        WebAgg backend. pip/easy_install may attempt to
                        install it after matplotlib.]
             pyparsing: yes [pyparsing was not found. It is required for
                        mathtext support. pip/easy_install may attempt to
                        install it after matplotlib.]
                 pycxx: yes [Couldn't import.  Using local copy.]
                libagg: yes [pkg-config information for 'libagg' could not
                        be found. Using local copy.]
              freetype: no  [pkg-config information for 'freetype2' could
                        not be found.]

The following required packages can not be built:

                    * freetype

Shouldn’t pip install -r requirements.txt also install freetype? How should freetype be installed in Ubuntu 12.04 so it works with matplotlib?


回答 0

否。pip不会安装系统级别的依赖项。这意味着pip将不会安装RPM(基于Redhat的系统)或DEB(基于Debian的系统)。

要安装系统依赖项,您将需要根据系统使用以下方法之一。

Ubuntu / Debian:

apt-get install libfreetype6-dev

要在基于Ubuntu / Debian的系统上搜索软件包:

apt-cache search <string>

例如:

apt-cache search freetype | grep dev

Redhat / CentOS / Fedora:

yum -y install freetype-devel

要在基于Redhat / CentOS / Fedora的系统上搜索软件包:

yum search <string>

例如:

yum search freetype | grep devel

Mac OS X的:通过自制

brew install freetype

在基于Mac OS X的系统上搜索软件包:

brew search <string>

例如:

brew search freetype

No. pip will not install system-level dependencies. This means pip will not install RPM(s) (Redhat based systems) or DEB(s) (Debian based systems).

To install system dependencies you will need to use one of the following methods depending on your system.

Ubuntu/Debian:

apt-get install libfreetype6-dev

To search for packages on Ubuntu/Debian based systems:

apt-cache search <string>

e.g:

apt-cache search freetype | grep dev

Redhat/CentOS/Fedora:

yum -y install freetype-devel

To search for packages on Redhat/CentOS/Fedora based systems:

yum search <string>

e.g:

yum search freetype | grep devel

Mac OS X: (via Homebrew)

brew install freetype

To search for packages on Mac OS X based systems:

brew search <string>

e.g:

brew search freetype

回答 1

我必须安装libxft-dev才能在ubuntu服务器14.04上启用matplotlib。

sudo apt-get install libfreetype6-dev libxft-dev

然后我可以使用

sudo easy_install matplotlib

I had to install libxft-dev in order to enable matplotlib on ubuntu server 14.04.

sudo apt-get install libfreetype6-dev libxft-dev

And then I could use

sudo easy_install matplotlib

回答 2

sudo apt-get install pkg-config在此github问题中发现一种解决方法。

A workaround is to do sudo apt-get install pkg-config which I found in this github issue.


回答 3

现有的答案都无法在Ubuntu上升级matplotlib。这最终对我有用:

$ sudo apt-get install build-dep python-matplotlib
$ pip install matplotlib --upgrade

None of the existing answers worked for me to upgrade matplotlib on Ubuntu. This is what ultimately work for me:

$ sudo apt-get install build-dep python-matplotlib
$ pip install matplotlib --upgrade

回答 4

此命令将下载所有依赖项。

对于python 2.x

sudo apt-get install python-matplotlib

对于python 3.x

sudo apt-get install python3-matplotlib

安装后,您可以尝试

(sudo) pip install matplotlib

This command will download all dependencies.

For python 2.x

sudo apt-get install python-matplotlib

For python 3.x

sudo apt-get install python3-matplotlib

After installing, you can try

(sudo) pip install matplotlib

回答 5

在Ubuntu上,安装blt-dev软件包后它可以工作。

$sudo apt-get install blt-dev
$pip install matplotlib

On Ubuntu, it worked after I installed blt-dev package.

$sudo apt-get install blt-dev
$pip install matplotlib

回答 6

我正在使用Mint,但以下答案均不适合我,我需要:

sudo apt-get install build-essential g++

I’m using Mint an none of this answers worked for me, I needed to:

sudo apt-get install build-essential g++

回答 7

我在Windows上使用Python 3.6时遇到了同样的问题,但是后来我切换到Python 3.5.2,一切正常。

I had the same issue with Python 3.6 on Windows, but then I switched to Python 3.5.2 and everything works fine.


回答 8

这个命令sudo apt-get install libfreetype6-dev对我来说在Ubuntu 16.04上失败了,
The following packages have unmet dependencies: libfreetype6-dev : Depends: libfreetype6 (= 2.6.1-0.1ubuntu2) but 2.6.1-0.1ubuntu2.3 is to be installed

因此,我从源代码下载了已安装的freetype ,请参考本指南

$ tar -xvjf freetype-x.y.tar.bz2  # extract the downloaded version file
$ cd freetype-x.y/ 
$ ./configure
$ make
$ sudo make install 

切换到virtualenv并且pip install matplotlib一切正常。

This command sudo apt-get install libfreetype6-dev failed for me on ubuntu 16.04,
The following packages have unmet dependencies: libfreetype6-dev : Depends: libfreetype6 (= 2.6.1-0.1ubuntu2) but 2.6.1-0.1ubuntu2.3 is to be installed

So I downloaded installed freetype from the source, credit to this guide

$ tar -xvjf freetype-x.y.tar.bz2  # extract the downloaded version file
$ cd freetype-x.y/ 
$ ./configure
$ make
$ sudo make install 

switched to virtualenv and pip install matplotlib and everything is working.


python中有内置的标识函数吗?

问题:python中有内置的标识函数吗?

我想指出一个什么都不做的函数:

def identity(*args)
    return args

我的用例是这样的

try:
    gettext.find(...)
    ...
    _ = gettext.gettext
else:
    _ = identity

当然,我可以使用identity上面定义的方法,但是内置方法肯定会运行得更快(并避免我自己引入的错误)​​。

显然,mapfilter使用None的身份,但这是具体到它们的实现。

>>> _=None
>>> _("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

I’d like to point to a function that does nothing:

def identity(*args)
    return args

my use case is something like this

try:
    gettext.find(...)
    ...
    _ = gettext.gettext
else:
    _ = identity

Of course, I could use the identity defined above, but a built-in would certainly run faster (and avoid bugs introduced by my own).

Apparently, map and filter use None for the identity, but this is specific to their implementations.

>>> _=None
>>> _("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

回答 0

做更多的研究,没有,没有一个功能,问题1673203被问到。来自Raymond Hettinger表示不会

最好让人们自己编写琐碎的传递,并考虑签名和时间成本。

因此实际上是一个更好的方法(lambda避免为函数命名):

_ = lambda *args: args
  • 优点:可以使用任意数量的参数
  • 缺点:结果是参数的盒装版本

要么

_ = lambda x: x
  • 优点:不会改变参数的类型
  • 缺点:只能使用1个位置参数

Doing some more research, there is none, a feature was asked in issue 1673203 And from Raymond Hettinger said there won’t be:

Better to let people write their own trivial pass-throughs and think about the signature and time costs.

So a better way to do it is actually (a lambda avoids naming the function):

_ = lambda *args: args
  • advantage: takes any number of parameters
  • disadvantage: the result is a boxed version of the parameters

OR

_ = lambda x: x
  • advantage: doesn’t change the type of the parameter
  • disadvantage: takes exactly 1 positional parameter

回答 1

https://en.wikipedia.org/wiki/Identity_function中定义的身份函数,它采用单个参数并返回不变:

def identity(x):
    return x

你要签名什么你问,当你说的def identity(*args)不是严格意义上的标识功能,只要你想它采取多个参数。很好,但是随后您遇到了一个问题,因为Python函数不会返回多个结果,因此您必须找到一种将所有这些参数塞入一个返回值的方法。

在Python中返回“多个值”的通常方法是返回值的元组-从技术上讲,这是一个返回值,但它可以在大多数情况下使用,就好像它是多个值一样。但是在这里做意味着你得到

>>> def mv_identity(*args):
...     return args
...
>>> mv_identity(1,2,3)
(1, 2, 3)
>>> # So far, so good. But what happens now with single arguments?
>>> mv_identity(1)
(1,)

快速解决问题会带来其他问题,如此处所示的各种答案。

因此,总而言之,Python中没有定义身份函数,因为:

  1. 形式定义(单个参数函数)不是那么有用,并且编写起来很简单。
  2. 通常,将定义扩展到多个参数的定义不是很好,因此最好定义自己的版本,使其适合您的特定情况。

为了您的确切情况,

def dummy_gettext(message):
    return message

几乎可以肯定是您想要的-一个具有相同的调用约定和return的函数,gettext.gettext该函数不变地返回其参数,并被明确命名以描述其作用以及打算在何处使用。如果性能在这里是至关重要的考虑因素,我会感到非常震惊。

An identity function, as defined in https://en.wikipedia.org/wiki/Identity_function, takes a single argument and returns it unchanged:

def identity(x):
    return x

What you are asking for when you say you want the signature def identity(*args) is not strictly an identity function, as you want it to take multiple arguments. That’s fine, but then you hit a problem as Python functions don’t return multiple results, so you have to find a way of cramming all of those arguments into one return value.

The usual way of returning “multiple values” in Python is to return a tuple of the values – technically that’s one return value but it can be used in most contexts as if it were multiple values. But doing that here means you get

>>> def mv_identity(*args):
...     return args
...
>>> mv_identity(1,2,3)
(1, 2, 3)
>>> # So far, so good. But what happens now with single arguments?
>>> mv_identity(1)
(1,)

And fixing that problem quickly gives other issues, as the various answers here have shown.

So, in summary, there’s no identity function defined in Python because:

  1. The formal definition (a single argument function) isn’t that useful, and is trivial to write.
  2. Extending the definition to multiple arguments is not well-defined in general, and you’re far better off defining your own version that works the way you need it to for your particular situation.

For your precise case,

def dummy_gettext(message):
    return message

is almost certainly what you want – a function that has the same calling convention and return as gettext.gettext, which returns its argument unchanged, and is clearly named to describe what it does and where it’s intended to be used. I’d be pretty shocked if performance were a crucial consideration here.


回答 2

你的会很好的。当参数数量固定后,您可以使用如下匿名函数:

lambda x: x

yours will work fine. When the number of parameters is fix you can use an anonymous function like this:

lambda x: x

回答 3

Python中没有内置的标识函数。Haskell id函数的模仿为:

identity = lambda x, *args: (x,) + args if args else x

用法示例:

identity(1)
1
identity(1,2)
(1, 2)

由于identity除了返回给定的参数外什么都不做,因此我认为它不会比本机实现慢。

There is no a built-in identity function in Python. An imitation of the Haskell’s id function would be:

identity = lambda x, *args: (x,) + args if args else x

Example usage:

identity(1)
1
identity(1,2)
(1, 2)

Since identity does nothing except returning the given arguments, I do not think that it is slower than a native implementation would be.


回答 4

不,没有。

请注意,您的identity

  1. 等价于lambda * args:args
  2. 将装箱参数-即

    In [6]: id = lambda *args: args
    
    In [7]: id(3)
    Out[7]: (3,)

因此,lambda arg: arg如果您需要真正的身份功能,则可能要使用。

注意:此示例将隐藏内置id函数(您可能永远不会使用)。

No, there isn’t.

Note that your identity:

  1. is equivalent to lambda *args: args
  2. Will box its args – i.e.

    In [6]: id = lambda *args: args
    
    In [7]: id(3)
    Out[7]: (3,)
    

So, you may want to use lambda arg: arg if you want a true identity function.

NB: This example will shadow the built-in id function (which you will probably never use).


回答 5

如果速度无关紧要,则应该处理所有情况:

def identity(*args, **kwargs):
    if not args:
        if not kwargs:
            return None
        elif len(kwargs) == 1:
            return  next(iter(kwargs.values()))
        else:
            return (*kwargs.values(),)
    elif not kwargs:
        if len(args) == 1:
            return args[0]
        else:
            return args
    else:
        return (*args, *kwargs.values())

用法示例:

print(identity())
None
$identity(1)
1
$ identity(1, 2)
(1, 2)
$ identity(1, b=2)
(1, 2)
$ identity(a=1, b=2)
(1, 2)
$ identity(1, 2, c=3)
(1, 2, 3)

If the speed does not matter, this should handle all cases:

def identity(*args, **kwargs):
    if not args:
        if not kwargs:
            return None
        elif len(kwargs) == 1:
            return  next(iter(kwargs.values()))
        else:
            return (*kwargs.values(),)
    elif not kwargs:
        if len(args) == 1:
            return args[0]
        else:
            return args
    else:
        return (*args, *kwargs.values())

Examples of usage:

print(identity())
None
$identity(1)
1
$ identity(1, 2)
(1, 2)
$ identity(1, b=2)
(1, 2)
$ identity(a=1, b=2)
(1, 2)
$ identity(1, 2, c=3)
(1, 2, 3)

回答 6

单参数函数的存根

gettext.gettext(OP的示例用例)接受单个参数message。如果一个人需要为它存根,没有理由退换货[message],而不是messagedef identity(*args): return args)。因此两者

_ = lambda message: message

def _(message):
    return message

伏贴。

…但是内置程序肯定会运行得更快(并避免我自己引入的错误)​​。

在这种琐碎的情况下,错误几乎无关紧要。对于预定义类型的参数,例如str,我们可以将str()其自身用作身份函数(因为通过字符串进行交互,它甚至保留了对象身份,请参见id下面的注释),并将其性能与lambda解决方案进行比较:

$ python3 -m timeit -s "f = lambda m: m" "f('foo')"
10000000 loops, best of 3: 0.0852 usec per loop
$ python3 -m timeit "str('foo')"
10000000 loops, best of 3: 0.107 usec per loop

微优化是可能的。例如,以下Cython代码:

test.pyx

cpdef str f(str message):
    return message

然后:

$ pip install runcython3
$ makecython3 test.pyx
$ python3 -m timeit -s "from test import f" "f('foo')"
10000000 loops, best of 3: 0.0317 usec per loop

内置对象识别功能

不要将身份函数与id返回对象“身份”的内置函数(该对象的唯一标识符,而不是与==运算符相比,该对象的值,而不是该对象的值)相混淆,后者是CPython中的内存地址。

Stub of a single-argument function

gettext.gettext (the OP’s example use case) accepts a single argument, message. If one needs a stub for it, there’s no reason to return [message] instead of message (def identity(*args): return args). Thus both

_ = lambda message: message

def _(message):
    return message

fit perfectly.

…but a built-in would certainly run faster (and avoid bugs introduced by my own).

Bugs in such a trivial case are barely relevant. For an argument of predefined type, say str, we can use str() itself as an identity function (because of string interning it even retains object identity, see id note below) and compare its performance with the lambda solution:

$ python3 -m timeit -s "f = lambda m: m" "f('foo')"
10000000 loops, best of 3: 0.0852 usec per loop
$ python3 -m timeit "str('foo')"
10000000 loops, best of 3: 0.107 usec per loop

A micro-optimisation is possible. For example, the following Cython code:

test.pyx

cpdef str f(str message):
    return message

Then:

$ pip install runcython3
$ makecython3 test.pyx
$ python3 -m timeit -s "from test import f" "f('foo')"
10000000 loops, best of 3: 0.0317 usec per loop

Build-in object identity function

Don’t confuse an identity function with the id built-in function which returns the ‘identity’ of an object (meaning a unique identifier for that particular object rather than that object’s value, as compared with == operator), its memory address in CPython.


回答 7

线程很旧。但是仍然想发布这个。

可以为参数和对象建立身份方法。在下面的示例中,ObjOut是ObjIn的标识。上面所有其他示例都没有处理dict ** wargs。

class test(object):
    def __init__(self,*args,**kwargs):
        self.args = args
        self.kwargs = kwargs
    def identity (self):
        return self

objIn=test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n')
objOut=objIn.identity()
print('args=',objOut.args,'kwargs=',objOut.kwargs)

#If you want just the arguments to be printed...
print(test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n').identity().args)
print(test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n').identity().kwargs)

$ py test.py
args= ('arg-1', 'arg-2', 'arg-3', 'arg-n') kwargs= {'key1': 1, 'keyn': 'n', 'key2': 2, 'key3': 3}
('arg-1', 'arg-2', 'arg-3', 'arg-n')
{'key1': 1, 'keyn': 'n', 'key2': 2, 'key3': 3}

The thread is pretty old. But still wanted to post this.

It is possible to build an identity method for both arguments and objects. In the example below, ObjOut is an identity for ObjIn. All other examples above haven’t dealt with dict **kwargs.

class test(object):
    def __init__(self,*args,**kwargs):
        self.args = args
        self.kwargs = kwargs
    def identity (self):
        return self

objIn=test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n')
objOut=objIn.identity()
print('args=',objOut.args,'kwargs=',objOut.kwargs)

#If you want just the arguments to be printed...
print(test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n').identity().args)
print(test('arg-1','arg-2','arg-3','arg-n',key1=1,key2=2,key3=3,keyn='n').identity().kwargs)

$ py test.py
args= ('arg-1', 'arg-2', 'arg-3', 'arg-n') kwargs= {'key1': 1, 'keyn': 'n', 'key2': 2, 'key3': 3}
('arg-1', 'arg-2', 'arg-3', 'arg-n')
{'key1': 1, 'keyn': 'n', 'key2': 2, 'key3': 3}

Python 2.7获取用户输入并以不带引号的字符串形式进行操作

问题:Python 2.7获取用户输入并以不带引号的字符串形式进行操作

我想从用户那里获取一个字符串,然后对其进行操作。

testVar = input("Ask user for something.")

没有我让用户在引号中键入其响应的方法,testVar是否可以成为字符串?即“你好”与你好

如果用户输入Hello,则会出现以下错误:

NameError:名称“ Hello”未定义

I want to get a string from a user, and then to manipulate it.

testVar = input("Ask user for something.")

Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. “Hello” vs. Hello

If the user types in Hello, I get the following error:

NameError: name ‘Hello’ is not defined


回答 0

使用raw_input()代替input()

testVar = raw_input("Ask user for something.")

input()实际上将输入评估为Python代码。我建议不要使用它。 raw_input()返回用户输入的逐字字符串。

Use raw_input() instead of input():

testVar = raw_input("Ask user for something.")

input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.


回答 1

该函数input还将评估刚读取为python代码的数据,这并不是您真正想要的。

通用方法是将(来自的sys.stdin)用户输入像其他文件一样对待。尝试

import sys
sys.stdin.readline()

如果您想使其简短,可以使用raw_input与相同的方法,input但忽略评估。

The function input will also evaluate the data it just read as python code, which is not really what you want.

The generic approach would be to treat the user input (from sys.stdin) like any other file. Try

import sys
sys.stdin.readline()

If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.


回答 2

我们可以raw_input()在Python 2和input()Python 3中使用该函数。默认情况下,输入函数采用字符串格式的输入。对于其他数据类型,您必须强制转换用户输入。

在Python 2中,我们使用raw_input()函数。它等待用户键入一些输入并按下,return然后我们需要通过将其强制转换为所需的数据类型来将值存储在变量中。使用类型转换时要小心

x = raw_input("Enter a number: ") #String input

x = int(raw_input("Enter a number: ")) #integer input

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

x = eval(raw_input("Enter a float number: ")) #eval input

在Python 3中,我们使用input()函数返回用户输入值。

x = input("Enter a number: ") #String input

如果输入字符串,则为int,float,eval,它将作为字符串输入

x = int(input("Enter a number: ")) #integer input

如果输入用于int cast的字符串 ValueError: invalid literal for int() with base 10:

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

如果输入用于float转换的字符串 ValueError: could not convert string to float

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

如果输入用于eval cast的字符串,那么NameError: name ' ' is not defined 这些错误也适用于Python 2。

We can use the raw_input() function in Python 2 and the input() function in Python 3. By default the input function takes an input in string format. For other data type you have to cast the user input.

In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting

x = raw_input("Enter a number: ") #String input

x = int(raw_input("Enter a number: ")) #integer input

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

x = eval(raw_input("Enter a float number: ")) #eval input

In Python 3 we use the input() function which returns a user input value.

x = input("Enter a number: ") #String input

If you enter a string, int, float, eval it will take as string input

x = int(input("Enter a number: ")) #integer input

If you enter a string for int cast ValueError: invalid literal for int() with base 10:

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

If you enter a string for float cast ValueError: could not convert string to float

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

If you enter a string for eval cast NameError: name ' ' is not defined Those error also applicable for Python 2.


回答 3

如果您想在python 2.x中使用input而不是raw_input,那么这个技巧将派上用场

    if hasattr(__builtins__, 'raw_input'):
      input=raw_input

之后,

testVar = input("Ask user for something.")

会很好。

If you want to use input instead of raw_input in python 2.x,then this trick will come handy

    if hasattr(__builtins__, 'raw_input'):
      input=raw_input

After which,

testVar = input("Ask user for something.")

will work just fine.


回答 4

testVar = raw_input("Ask user for something.")
testVar = raw_input("Ask user for something.")

回答 5

我的修正工作代码:

import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)

correct= False
while(correct == False):
    guess1= input("Which number is the highest? "+ str(list) + ": ")
    if maxNum == guess1:
        print("Correct!")
        correct = True
    else:
        print("Incorrect, try again")

correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
     print("Correct!")
     correct = True
else:
    print("Incorrect, try again")

correct= False
while(correct == False):
    guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
    if sqrtOne >= 2.0 and str(guess3) == "y":
        print("Correct!")
        correct = True
    elif sqrtOne < 2.0 and str(guess3) == "n":
        print("Correct!")
        correct = True
    else:
        print("Incorrect, try again")

print("Thanks for playing!")

My Working code with fixes:

import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)

correct= False
while(correct == False):
    guess1= input("Which number is the highest? "+ str(list) + ": ")
    if maxNum == guess1:
        print("Correct!")
        correct = True
    else:
        print("Incorrect, try again")

correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
     print("Correct!")
     correct = True
else:
    print("Incorrect, try again")

correct= False
while(correct == False):
    guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
    if sqrtOne >= 2.0 and str(guess3) == "y":
        print("Correct!")
        correct = True
    elif sqrtOne < 2.0 and str(guess3) == "n":
        print("Correct!")
        correct = True
    else:
        print("Incorrect, try again")

print("Thanks for playing!")

回答 6

这是我的工作,以防万一我将来需要转移到python 3时失败。

def _input(msg):
  return raw_input(msg)

This is my work around to fail safe in case if i will need to move to python 3 in future.

def _input(msg):
  return raw_input(msg)

回答 7

该问题似乎在Python 3.4.2版中已解决。

testVar = input("Ask user for something.")

将正常工作。

The issue seems to be resolved in Python version 3.4.2.

testVar = input("Ask user for something.")

Will work fine.


使用Pandas在python中读取Excel文件

问题:使用Pandas在python中读取Excel文件

我正在尝试以这种方式读取Excel文件:

newFile = pd.ExcelFile(PATH\FileName.xlsx)
ParsedData = pd.io.parsers.ExcelFile.parse(newFile)

这引发了一个错误,该错误表示预期有两个参数,我不知道第二个参数是什么,而且我在这里想要实现的是将Excel文件转换为DataFrame,我这样做是否正确?或者还有其他方法可以使用熊猫吗?

I am trying to read an excel file this way :

newFile = pd.ExcelFile(PATH\FileName.xlsx)
ParsedData = pd.io.parsers.ExcelFile.parse(newFile)

which throws an error that says two arguments expected, I don’t know what the second argument is and also what I am trying to achieve here is to convert an Excel file to a DataFrame, Am I doing it the right way? or is there any other way to do this using pandas?


回答 0

关闭:首先调用ExcelFile,然后调用该.parse方法并将表单名称传递给该方法。

>>> xl = pd.ExcelFile("dummydata.xlsx")
>>> xl.sheet_names
[u'Sheet1', u'Sheet2', u'Sheet3']
>>> df = xl.parse("Sheet1")
>>> df.head()
                  Tid  dummy1    dummy2    dummy3    dummy4    dummy5  \
0 2006-09-01 00:00:00       0  5.894611  0.605211  3.842871  8.265307   
1 2006-09-01 01:00:00       0  5.712107  0.605211  3.416617  8.301360   
2 2006-09-01 02:00:00       0  5.105300  0.605211  3.090865  8.335395   
3 2006-09-01 03:00:00       0  4.098209  0.605211  3.198452  8.170187   
4 2006-09-01 04:00:00       0  3.338196  0.605211  2.970015  7.765058   

     dummy6  dummy7    dummy8    dummy9  
0  0.623354       0  2.579108  2.681728  
1  0.554211       0  7.210000  3.028614  
2  0.567841       0  6.940000  3.644147  
3  0.581470       0  6.630000  4.016155  
4  0.595100       0  6.350000  3.974442  

您正在做的是调用驻留在类本身而不是实例上的方法,这是可以的(尽管不是很惯用),但是如果这样做,则还需要传递工作表名称:

>>> parsed = pd.io.parsers.ExcelFile.parse(xl, "Sheet1")
>>> parsed.columns
Index([u'Tid', u'dummy1', u'dummy2', u'dummy3', u'dummy4', u'dummy5', u'dummy6', u'dummy7', u'dummy8', u'dummy9'], dtype=object)

Close: first you call ExcelFile, but then you call the .parse method and pass it the sheet name.

>>> xl = pd.ExcelFile("dummydata.xlsx")
>>> xl.sheet_names
[u'Sheet1', u'Sheet2', u'Sheet3']
>>> df = xl.parse("Sheet1")
>>> df.head()
                  Tid  dummy1    dummy2    dummy3    dummy4    dummy5  \
0 2006-09-01 00:00:00       0  5.894611  0.605211  3.842871  8.265307   
1 2006-09-01 01:00:00       0  5.712107  0.605211  3.416617  8.301360   
2 2006-09-01 02:00:00       0  5.105300  0.605211  3.090865  8.335395   
3 2006-09-01 03:00:00       0  4.098209  0.605211  3.198452  8.170187   
4 2006-09-01 04:00:00       0  3.338196  0.605211  2.970015  7.765058   

     dummy6  dummy7    dummy8    dummy9  
0  0.623354       0  2.579108  2.681728  
1  0.554211       0  7.210000  3.028614  
2  0.567841       0  6.940000  3.644147  
3  0.581470       0  6.630000  4.016155  
4  0.595100       0  6.350000  3.974442  

What you’re doing is calling the method which lives on the class itself, rather than the instance, which is okay (although not very idiomatic), but if you’re doing that you would also need to pass the sheet name:

>>> parsed = pd.io.parsers.ExcelFile.parse(xl, "Sheet1")
>>> parsed.columns
Index([u'Tid', u'dummy1', u'dummy2', u'dummy3', u'dummy4', u'dummy5', u'dummy6', u'dummy7', u'dummy8', u'dummy9'], dtype=object)

回答 1

这是非常简单的方法。

import pandas
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname='Sheet 1')
# or using sheet index starting 0
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname=2)

查看文档的完整详细信息 http://pandas.pydata.org/pandas-docs/version/0.17.1/genic/pandas.read_excel.html

FutureWarning:sheetname对于较新的Pandas版本,不推荐使用该关键字,请sheet_name改用。

This is much simple and easy way.

import pandas
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname='Sheet 1')
# or using sheet index starting 0
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname=2)

check out documentation full details http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.read_excel.html

FutureWarning: The sheetname keyword is deprecated for newer Pandas versions, use sheet_name instead.


回答 2

以为我应该在这里添加,如果要访问行或列以遍历它们,可以执行以下操作:

import pandas as pd

# open the file
xlsx = pd.ExcelFile(PATH\FileName.xlsx)

# get the first sheet as an object
sheet1 = xlsx.parse(0)

# get the first column as a list you can loop through
# where the is 0 in the code below change to the row or column number you want    
column = sheet1.icol(0).real

# get the first row as a list you can loop through
row = sheet1.irow(0).real

编辑:

现在不推荐使用方法icol(i)irow(i)。您可以使用sheet1.iloc[:,i]获取第i sheet1.iloc[i,:]行和获取第i行。

Thought i should add here, that if you want to access rows or columns to loop through them, you do this:

import pandas as pd

# open the file
xlsx = pd.ExcelFile(PATH\FileName.xlsx)

# get the first sheet as an object
sheet1 = xlsx.parse(0)

# get the first column as a list you can loop through
# where the is 0 in the code below change to the row or column number you want    
column = sheet1.icol(0).real

# get the first row as a list you can loop through
row = sheet1.irow(0).real

Edit:

The methods icol(i) and irow(i) are deprecated now. You can use sheet1.iloc[:,i] to get the i-th col and sheet1.iloc[i,:] to get the i-th row.


回答 3

我认为这应该可以满足您的需求:

import pandas as pd

# Read the excel sheet to pandas dataframe
DataFrame = pd.read_excel("PATH\FileName.xlsx", sheetname=0)

I think this should satisfy your need:

import pandas as pd

# Read the excel sheet to pandas dataframe
df = pd.read_excel("PATH\FileName.xlsx", sheetname=0)

回答 4

您只需要将文件的路径提供给 pd.read_excel

import pandas as pd

file_path = "./my_excel.xlsx"
data_frame = pd.read_excel(file_path)

检出文档以浏览参数,例如skiprows在加载Excel时忽略行

You just need to feed the path to your file to pd.read_excel

import pandas as pd

file_path = "./my_excel.xlsx"
data_frame = pd.read_excel(file_path)

Checkout the documentation to explore parameters like skiprows to ignore rows when loading the excel


回答 5

import pandas as pd

data = pd.read_excel (r'**YourPath**.xlsx')

print (data)
import pandas as pd

data = pd.read_excel (r'**YourPath**.xlsx')

print (data)

回答 6

这是语法更新的方法,在python代码中更常见。它还可以防止您多次打开同一文件。

import pandas as pd

sheet1, sheet2 = None, None
with pd.ExcelFile("PATH\FileName.xlsx") as reader:
    sheet1 = pd.read_excel(reader, sheet_name='Sheet1')
    sheet2 = pd.read_excel(reader, sheet_name='Sheet2')

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html

Here is an updated method with syntax that is more common in python code. It also prevents you from opening the same file multiple times.

import pandas as pd

sheet1, sheet2 = None, None
with pd.ExcelFile("PATH\FileName.xlsx") as reader:
    sheet1 = pd.read_excel(reader, sheet_name='Sheet1')
    sheet2 = pd.read_excel(reader, sheet_name='Sheet2')

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html