标签归档:syntax-error

语法错误:不是机会

问题:语法错误:不是机会

我尝试在python IDLE中执行以下代码

from __future__ import braces 

我得到了以下错误:

SyntaxError: not a chance

上述错误是什么意思?

I tried executed the following code in the python IDLE

from __future__ import braces 

And I got the following error:

SyntaxError: not a chance

What does the above error mean?


回答 0

您已经在Python中找到了一个复活节彩蛋。开个玩笑。

这意味着永远不会实现用大括号而不是缩进来分隔块。

通常,从特殊__future__模块导入会启用向后不兼容的print()功能,例如功能或真正的划分。

因此,线from __future__ import braces被认为是指你要启用该功能“用括号来创建块”,异常告诉您那的机会不断发生的零。

您可以添加到包括在Python中-笑话的一大串,就像import __hello__import thisimport antigravity。Python开发人员具有良好的幽默感!

You have found an easter egg in Python. It is a joke.

It means that delimiting blocks by braces instead of indentation will never be implemented.

Normally, imports from the special __future__ module enable features that are backwards-incompatible, such as the print() function, or true division.

So the line from __future__ import braces is taken to mean you want to enable the ‘create blocks with braces’ feature, and the exception tells you your chances of that ever happening are nil.

You can add that to the long list of in-jokes included in Python, just like import __hello__, import this and import antigravity. The Python developers have a well-developed sense of humour!


回答 1

__future__模块通常用于提供Python未来版本的功能。

这是一个复活节彩蛋,总结了开发人员在此问题上的感受。

还有更多:

import this 将显示Python的禅宗。

import __hello__将显示Hello World...

在Python 2.7和3.0中,import antigravity将打开浏览器以显示漫画!

The __future__ module is normally used to provide features from future versions of Python.

This is an easter egg that summarizes its developers’ feelings on this issue.

There are several more:

import this will display the zen of Python.

import __hello__ will display Hello World....

In Python 2.7 and 3.0, import antigravity will open the browser to a comic!


与python中的“意外缩进”怎么办?

问题:与python中的“意外缩进”怎么办?

如何纠正python中的“意外缩进”错误?

How do I rectify the error “unexpected indent” in python?


回答 0

Python在行的开头使用空格来确定代码块的开始和结束时间。您可以获得的错误是:

意外缩进。这行代码的开头比以前的空格多,但前面的不是子块的开头(例如if / while / for语句)。块中的所有代码行必须以完全相同的空格字符串开头。例如:

>>> def a():
...   print "foo"
...     print "bar"
IndentationError: unexpected indent

当以交互方式运行python时,这一点尤其常见:请确保不要在命令前放置任何多余的空格。(在复制粘贴示例代码时非常烦人!)

>>>   print "hello"
IndentationError: unexpected indent

Unindent与任何外部缩进级别都不匹配。这行代码的开头空格比以前的空格少,但是同样,它与它可能包含的任何其他块也不匹配。Python无法决定其去向。例如,在下面,最终的打印是否应该包含在if子句中?

>>> if user == "Joey":
...     print "Super secret powers enabled!"
...   print "Revealing super secrets"
IndendationError: unindent does not match any outer indentation level

预期缩进的块。这行代码的开头与前面的空格数量相同,但是最后一行应开始一个块(例如,if / while / for语句,函数定义)。

>>> def foo():
... print "Bar"
IndentationError: expected an indented block

如果您想要一个不执行任何操作的函数,请使用“ no-op”命令传递

>>> def foo():
...     pass

允许混合使用制表符和空格(至少在我的Python版本中),但是Python假定制表符的长度为8个字符,可能与您的编辑器不匹配。只需对标签说“不”即可。大多数编辑器允许将它们自动替换为空格。

避免这些问题的最佳方法是在缩进子块时始终使用一致数量的空格,并且理想情况下使用可以为您解决问题的良好IDE。这也将使您的代码更具可读性。

Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are:

Unexpected indent. This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g. if/while/for statement). All lines of code in a block must start with exactly the same string of whitespace. For instance:

>>> def a():
...   print "foo"
...     print "bar"
IndentationError: unexpected indent

This one is especially common when running python interactively: make sure you don’t put any extra spaces before your commands. (Very annoying when copy-and-pasting example code!)

>>>   print "hello"
IndentationError: unexpected indent

Unindent does not match any outer indentation level. This line of code has fewer spaces at the start than the one before, but equally it does not match any other block it could be part of. Python cannot decide where it goes. For instance, in the following, is the final print supposed to be part of the if clause, or not?

>>> if user == "Joey":
...     print "Super secret powers enabled!"
...   print "Revealing super secrets"
IndendationError: unindent does not match any outer indentation level

Expected an indented block. This line of code has the same number of spaces at the start as the one before, but the last line was expected to start a block (e.g. if/while/for statement, function definition).

>>> def foo():
... print "Bar"
IndentationError: expected an indented block

If you want a function that doesn’t do anything, use the “no-op” command pass:

>>> def foo():
...     pass

Mixing tabs and spaces is allowed (at least on my version of Python), but Python assumes tabs are 8 characters long, which may not match your editor. Just say “no” to tabs. Most editors allow them to be automatically replaced by spaces.

The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock, and ideally use a good IDE that solves the problem for you. This will also make your code more readable.


回答 1

在Python中,间距非常重要,这给出了代码块的结构。当您弄乱代码结构时会发生此错误,例如:

def test_function() :
   if 5 > 3 :
   print "hello"

您的文件中可能还会包含选项卡和空格。

我建议您使用python语法感知编辑器,例如PyScripterNetbeans

In Python, the spacing is very important, this gives the structure of your code blocks. This error happens when you mess up your code structure, for example like this :

def test_function() :
   if 5 > 3 :
   print "hello"

You may also have a mix of tabs and spaces in your file.

I suggest you use a python syntax aware editor like PyScripter, or Netbeans


回答 2

使用-tt选项运行您的代码,以查明您是否不一致地使用了制表符和空格

Run your code with the -tt option to find out if you are using tabs and spaces inconsistently


回答 3

在使用的任何编辑器中打开可见的空白,并打开带空格的替换选项卡。

虽然可以将选项卡与Python混合使用,但通常将选项卡和空格混合会导致您遇到错误。建议使用4个空格替换制表符,这是编写Python代码的推荐方法。

Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.

While you can use tabs with Python mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with 4 spaces is the recommended approach for writing Python code.


回答 4

通过使用正确的缩进。Python具有空格意识,因此您需要按照其块的缩进指南进行操作,否则会出现缩进错误。

By using correct indentation. Python is whitespace aware, so you need to follow its indentation guidlines for blocks or you’ll get indentation errors.


回答 5

如果您使用Sublime编写Python并出现缩进错误,

查看->缩进->将缩进转换为空格

我描述的问题是由Sublime文本编辑器引起的。同样的问题也可能由其他编辑器引起。从本质上讲,这个问题与Python希望以空格来处理缩进有关,而各种编辑器都以制表符来编写缩进。

If you’re writing Python using Sublime and getting indentation errors,

view -> indentation -> convert indentation to spaces

The issue I’m describing is caused by the Sublime text editor. The same issue could be caused by other editors as well. Essentially, the issue has to do with Python wanting to treat indentations in terms of spaces versus various editors coding the indentations in terms of tabs.


回答 6

确保在编辑器中使用选项“插入空格而不是制表符”。然后,您可以选择所需的制表符宽度,例如4。您可以在gedit中的edit-> preferences-> editor下找到这些选项。

底线:使用空间而不是选项卡

Make sure you use the option “insert spaces instead of tabs” in your editor. Then you can choose you want a tab width of, for example 4. You can find those options in gedit under edit–>preferences–>editor.

bottom line: USE SPACES not tabs


回答 7

将某些内容粘贴到Python解释器(终端/控制台)中时,也会发生此错误。

请注意,解释器会将空行解释为表达式的末尾,因此如果您粘贴类似

def my_function():
    x = 3

    y = 7

解释器将在解释之前将空行解释y = 7为表达式的末尾,也就是说,您已经完成了对函数的定义,而下一行- y = 7由于它是新表达式,因此缩进不正确。

This error can also occur when pasting something into the Python interpreter (terminal/console).

Note that the interpreter interprets an empty line as the end of an expression, so if you paste in something like

def my_function():
    x = 3

    y = 7

the interpreter will interpret the empty line before y = 7 as the end of the expression, i.e. that you’re done defining your function, and the next line – y = 7 will have incorrect indentation because it is a new expression.


回答 8

似乎没有提到的一个问题是,由于与缩进无关的代码问题,此错误可能会出现。

例如,使用以下脚本:

def add_one(x):
    try:
        return x + 1
add_one(5)

IndentationError: unexpected unindent当问题当然是缺少except:语句时,这将返回。

我的观点:检查上面报告意外(un)缩进的代码!

One issue which doesn’t seem to have been mentioned is that this error can crop up due to a problem with the code that has nothing to do with indentation.

For example, take the following script:

def add_one(x):
    try:
        return x + 1
add_one(5)

This returns an IndentationError: unexpected unindent when the problem is of course a missing except: statement.

My point: check the code above where the unexpected (un)indent is reported!


回答 9

如果缩进没问题,请查看您的编辑器是否具有“查看空白”选项。启用它应该可以找到空格和制表符混合的位置。

If the indentation looks ok then have a look to see if your editor has a “View Whitespace” option. Enabling this should allow to find where spaces and tabs are mixed.


回答 10

有一个对我总是有用的技巧:

如果您意外缩进,并且发现所有代码均已缩进,请尝试使用其他编辑器将其打开,然后您会看到未缩进的代码行。

当我使用vim,gedit或类似的编辑器时,这件事发生在我身上。

尝试仅将1个编辑器用于您的代码。

There is a trick that always worked for me:

If you got and unexpected indent and you see that all the code is perfectly indented, try opening it with another editor and you will see what line of code is not indented.

It happened to me when used vim, gedit or editors like that.

Try to use only 1 editor for your code.


回答 11

只需复制您的脚本,然后在整个代码“””下放入“”即可…

在变量中指定此行。

a = """ your python script """
print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

现在在Sublime Editor中使用ctrl + b执行此代码,现在它将在控制台中打印缩进的代码。而已

Simply copy your script and put under “”” your entire code “”” …

specify this line in a variable.. like,

a = """ your python script """
print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in Sublime Editor using ctrl+b, now it will print indented code in console. that’s it


回答 12

您需要做的就是从以下代码的开头删除空格或制表符空格

from django.contrib import admin

# Register your models here.
from .models import Myapp
admin.site.register(Myapp)

All You need to do is remove spaces or tab spaces from the start of following codes

from django.contrib import admin

# Register your models here.
from .models import Myapp
admin.site.register(Myapp)

回答 13

运行以下命令以解决该问题:

autopep8 -i <filename>.py

这将更新您的代码并解决所有缩进错误:)

希望这能解决

Run the following command to get it solved :

autopep8 -i <filename>.py

This will update your code and solve all indentation Errors :)

Hope this will solve


回答 14

Notepad ++提供了正确的制表符空间,但最终在Sublime文本编辑器中发现了缩进问题。

使用Sublime文本编辑器并逐行进行

Notepad++ was giving the tab space correct but the indentation problem was finally found in Sublime text editor.

Use Sublime text editor and go line by line


回答 15

与许多其他编程语言不同,Python中的缩进很重要,这并不是为了代码可读性。如果连续命令之间的代码中有空格或制表符,则python将给出此错误,因为Python对此很敏感。当我们将代码复制并粘贴到任何Python时,我们很可能会遇到此错误。 确保使用文本编辑器(如Notepad ++)标识并删除这些空格,或者从出现错误的代码行中手动删除空格。

Step1 :Gives error 
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])

Step2: L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]print(L[2: ])

Step3: No error after space was removed
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])
OUTPUT: [[7, 8, 9, 10]]

谢谢!

Indentation in Python is important and this is just not for code readability, unlike many other programming languages. If there is any white space or tab in your code between consecutive commands, python will give this error as Python is sensitive to this. We are likely to get this error when we do copy and paste of code to any Python. Make sure to identify and remove these spaces using a text editor like Notepad++ or manually remove the whitespace from the line of code where you are getting an error.

Step1 :Gives error 
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])

Step2: L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]print(L[2: ])

Step3: No error after space was removed
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print(L[2: ])
OUTPUT: [[7, 8, 9, 10]]

Thanks!


如何在自动生成的manage.py上解决SyntaxError?

问题:如何在自动生成的manage.py上解决SyntaxError?

我正在遵循Django教程https://docs.djangoproject.com/es/1.10/intro/tutorial01/

我创建了一个“ mysite”虚拟项目(我的第一个项目),并尝试对其进行测试而未对其进行更改。

django-admin startproject mysite
cd mysite
python manage.py runserver

File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax

我在系统本身生成的文件上收到SyntaxError。而且我似乎找不到其他遇到过同样问题的人。

如果可能有用,我将添加一些设置数据

$ vpython --version
Python 2.7.12
$ pip --version
pip 9.0.1 from /home/frank/.local/lib/python2.7/site-packages (python 2.7)
$ python -m django --version
1.10.6

有人能帮帮我吗?

更新:添加自动生成的manage.py的内容

cat manage.py 
#!/usr/bin/env python3
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

I’m following the Django tutorial https://docs.djangoproject.com/es/1.10/intro/tutorial01/

I’ve created a “mysite” dummy project (my very first one) and try to test it without altering it.

django-admin startproject mysite
cd mysite
python manage.py runserver

File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax

I’m getting a SyntaxError on a file that was generated by the system itself. And I seem unable to find anyone else who has gone through the same issue.

I’ll add some data of my setup in case it may be of use

$ vpython --version
Python 2.7.12
$ pip --version
pip 9.0.1 from /home/frank/.local/lib/python2.7/site-packages (python 2.7)
$ python -m django --version
1.10.6

Can somebody please help me?

Update: adding contents of autogenerated manage.py

cat manage.py 
#!/usr/bin/env python3
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

回答 0

确保将Django连接到哪个python版本(如果使用任何版本,请确保激活虚拟环境)。

当您仅使用django安装时

pip install django 

那你必须跑

python manage.py startapp <yourApp name>

否则,如果您使用过:

pip3 install django

那你必须跑

python3 manage.py startapp <yourapp name>

参考:

Make sure which python version you connect the django with (Make sure to activate the virtual env if you are using any).

When you install django using just

pip install django 

then you have to run

python manage.py startapp <yourApp name>

else if you have used:

pip3 install django

then you have to run

python3 manage.py startapp <yourapp name>

Refer:


回答 1

您可以尝试使用python3 manage.py runserver。这个对我有用。

You can try with python3 manage.py runserver. It works for me.


回答 2

您应该激活虚拟环境。在终端->源env / bin / activate中,现在将在您的终端中显示—–(env)!

现在它将工作-> runserver。

无需删除部分!

you should activate your virtual environment . In terminal -> source env/bin/activate now there will be —-> (env) in your terminal displayed !

now it will work -> runserver .

No need to delete exc part !


回答 3

我遇到了相同的情况,但这通过使用特定的python 3.6来解决,如下所示:

python3.6 manage.py runserver

I was experiencing the same but this was solved by running with specific python 3.6 as below:

python3.6 manage.py runserver

回答 4

只需激活您的虚拟环境即可。

Just activate your virtual environment.


回答 5

这是我遇到的一个简单解决方案。您是否激活了虚拟环境?

我的终端截图

Its a simple solution actually one i just ran into. Did you activate your virtual environment?

my terminal screenshot


回答 6

最好创建一个虚拟环境并在该虚拟环境中运行Django代码,这有助于不更改现有环境。这是从虚拟环境和Django开始的基本步骤。

  1. 创建一个新目录并CD进入。

    mkdir testcd test

  2. 安装和创建虚拟环境。

    python3 -m pip install virtualenv virtualenv venv -p python3

  3. 激活虚拟环境: source venv/bin/activate

  4. 安装Django: pip install django

  5. 开始一个新项目: django-admin startproject myproject

  6. cd到您的项目并运行Project:

    cd myprojectpython manage.py runserver

  7. 您可以在这里看到您的项目: http://127.0.0.1:8000/

It’s best to create a virtual environment and run your Django code inside this virtual environment, this helps in not changing your existing environments. Here are the basic steps to start with the virtual environment and Django.

  1. Create a new Directory and cd into it.

    mkdir test , cd test

  2. Install and Create a Virtual environment.

    python3 -m pip install virtualenv virtualenv venv -p python3

  3. Activate Virtual Environment: source venv/bin/activate

  4. Install Django: pip install django

  5. Start a new project: django-admin startproject myproject

  6. cd to your project and Run Project:

    cd myproject , python manage.py runserver

  7. You can see your project here : http://127.0.0.1:8000/


回答 7

经过精确的指令测试(使用python2或python3而不是仅仅使用“ python”),我认为无论本教程怎么说,这仅适用于python3。

After testing with precise instructions (using python2 or python3 instead of just “python”) I’ve constated that no matter what the tutorial says, this works ONLY with python3.


回答 8

要运行Python版本3,您需要使用python3而不是python

因此,最终命令将是:

python3 manage.py runserver

For running Python version 3, you need to use python3 instead of python.

So, the final command will be:

python3 manage.py runserver

回答 9

解决方案很简单。来自manage.py的exceptions是因为当使用python运行命令时,Django无法预测确切的python版本,例如您可能具有3.6、3.5、3.8,并且可能只有此版本之一pip模块用于安装Django来解决这两种使用:

./manage.py `enter code here`<command>

或使用确切的python版本(xx)表示:

pythonx.x manage.py <command>

否则,使用虚拟环境会派上用场,因为它可以轻松将任何pip django模块与python版本相关联

  • 用pyenv或virtualenv创建环境
  • 激活(例如在virtualenv => virtualenv env中)
  • 使用python manage.py命令运行

The solution is straightforward. the exception from manage.py is because when running the command with python, Django is unable to predict the exact python version, say you may have 3.6, 3.5, 3.8 and maybe just one of this versions pip module was used to install Django to resolve this either use:

./manage.py `enter code here`<command>

or using the exact python version(x.x) stands:

pythonx.x manage.py <command>

else the use of virtual environments can come in handy because its relates any pip django module easily to python version

  • create env with pyenv or virtualenv
  • activate (e.g in virtualenv => virtualenv env)
  • run using python manage.py command

回答 10

您必须激活已安装django的虚拟环境。然后运行此命令-python manage.py runserver

You must activate virtual environment where you have installed django. Then run this command – python manage.py runserver


回答 11

我解决了同样的情况。

安装版本

python 3.6,django 2.1

情况

我在Windows 10中安装了Node.js。 python manage.py runserver导致错误之后。

错误

File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax

原因

我的python路径从python-3.6更改为python-2.7。(3.6在我的电脑上是正确的。)

修复python路径。

I solved same situation.

INSTALLED VERSION

python 3.6, django 2.1

SITUATION

I installed Node.js in Windows 10. After python manage.py runserver caused error.

ERROR

File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax

REASON

My python path changed to python-2.7 from python-3.6. (3.6 is correct in my PC.)

SOLUTION

Fix python path.


回答 12

我遇到了完全相同的错误,但是后来我发现我忘记激活装有django和其他必需软件包的conda环境。

解决方案:创建安装了django的conda或虚拟环境,并在使用以下命令之前将其激活: $ python manage.py migrate

I had the exact same error, but then I later found out that I forget to activate the conda environment which had django and other required packages installed.

Solution: Create a conda or virtual environment with django installed, and activate it before you use the command: $ python manage.py migrate


回答 13

django-admin可能是错误的文件。我遇到了相同的问题,在另一台计算机上找不到相同的设置流程。

比较两个项目后,我在manage.py和settings.py中发现了一些区别,然后我意识到我创建了2.0 django项目,但使用python2运行了该项目。

which django-admin在iterm中运行

/Library/Frameworks/Python.framework/Versions/3.6/bin/django-admin

看起来我在python3中有一个django-admin,但我不知道为什么,所以我尝试获取正确的django-amin。

pip show django

然后我得到了

Name: Django
Version: 1.11a1
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD
Location: /Library/Python/2.7/site-packages
Requires: pytz

在中/Library/Python/2.7/site-packages,我找到了django-admin

/Library/Python/2.7/site-packages/django/bin/django-admin.py

所以我再次创建了项目

/Library/Python/2.7/site-packages/django/bin/django-admin.py startproject myproject

然后跑

cd myproject
python manage.py runserver

成功🎉

The django-admin maybe the wrong file.I met the same problem which I did not found on a different computer the same set-up flow.

After comparing two project, I found several difference at manage.py and settings.py, then I realized I created 2.0 django project but run it with python2.

runwhich django-adminin iterm

/Library/Frameworks/Python.framework/Versions/3.6/bin/django-admin

It looks like I got a django-admin in python3 which I didn’t know why.So I tried to get the correct django-amin.

pip show django

then I got

Name: Django
Version: 1.11a1
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD
Location: /Library/Python/2.7/site-packages
Requires: pytz

In/Library/Python/2.7/site-packages, I found the django-admin

/Library/Python/2.7/site-packages/django/bin/django-admin.py

So I created project again by

/Library/Python/2.7/site-packages/django/bin/django-admin.py startproject myproject

then run

cd myproject
python manage.py runserver

succeeded🎉


回答 14

我们必须在项目内部而不是在项目外部创建一个虚拟环境。

We have to create a virtual environment inside the project, not outside the project.. Then it will solve..


回答 15

看来您的计算机上有多个版本的Python。尝试删除其中一个,并保留唯一用于开发应用程序的版本。

如果需要,您可以升级您的版本,但请确保您的计算机上只有一个Python版本。

我希望这有帮助。

It seems you have more than one version of Python on your computer. Try and remove one and leave the only version you used to develop your application.

If need be, you can upgrade your version, but ensure you have only one version of Python on your computer.

I hope this helps.


回答 16

我遇到了同样的异常,因为我忘记了激活虚拟环境。

I landed on the same exact exception because I forgot to activate the virtual environment.


回答 17

可能是以下原因造成的,

1. The virtual environment is not enabled
2. The virtual environment is enabled but the python version is different

创建虚拟环境

$ virtualenv --python=python3 venv

激活虚拟环境

$ source venv/bin/activate

The following could be the possible reasons,

1. The virtual environment is not enabled
2. The virtual environment is enabled but the python version is different

To create virtual environment

$ virtualenv --python=python3 venv

To activate the virtual environment

$ source venv/bin/activate

回答 18

我也遇到了同样的错误。

然后,我回到了环境文件夹所在的文件夹,却忘记了激活虚拟环境,因此只有我遇到了此错误。

转到该文件夹​​并激活虚拟环境。

$ source env/bin/activate

I was also getting the same error.

Then I went back to the folder where the environment folder is there and I forgot to activate a Virtual environment so only I was getting this error.

Go to that folder and activate the virtual environment.

$ source env/bin/activate

回答 19

另外,本教程还建议使用虚拟环境(请参阅Django文档:https : //docs.djangoproject.com/en/2.0/topics/install/#installing-official-release “)。您可以使用pipenv --three。您已经安装django pipenv install django并使用激活了虚拟环境pipenv shell,执行时python将引用python3python manage.py runserver

Pipenv文档:https://pipenv.kennethreitz.org/

Also, the tutorial recommends that a virtual environment is used (see Django documentation: https://docs.djangoproject.com/en/2.0/topics/install/#installing-official-release“). You can do this with pipenv --three. Once you’ve installed django with pipenv install django and activated your virtual environment with pipenv shell, python will refer to python3 when executing python manage.py runserver.

Pipenv documentation: https://pipenv.kennethreitz.org/


回答 20

我想知道的是,虽然django已安装到容器中,但它可能不在您运行命令的主机中。然后该命令将如何运行。因此,由于没有上述解决方案对我有用。

我找到了运行中的容器并使用进入了运行中的容器,docker exec -it <container> bash 然后在docker容器中运行了命令。当我们拥有大容量的容器时,所做的更改也会在本地反映出来。可以运行的命令都可以在运行容器中运行

What am I wondering is though the django is installed to the container it may not be in the host machine where you are running the command. Then how will the command run. So since no above solutions worked for me.

I found out the running container and get into the running container using docker exec -it <container> bash then ran the command inside docker container. As we have the volumed container the changes done will also reflect locally. What ever command is to be run can be run inside the running container


回答 21

对于将来的读者,我也有同样的问题。原来直接从网站安装Python以及Anaconda的另一个版本导致了此问题。我必须卸载Python2.7并仅保留anaconda作为唯一发行版。

For future readers, I too had the same issue. Turns out installing Python directly from website as well as having another version from Anaconda caused this issue. I had to uninstall Python2.7 and only keep anaconda as the sole distribution.


回答 22

您是否已进入django的虚拟环境?运行python -m venv myvenv,如果你还没有安装。

Have you entered the virtual environment for django? Run python -m venv myvenv if you have not yet installed.


回答 23

做就是了:

pipenv shell

然后重复:

python manage.py runserver

并且请勿from exc按照上述建议删除。

干杯!

Just do:

pipenv shell

then repeat:

python manage.py runserver

and don’t delete from exc as suggested above.

cheers!


回答 24

我有同样的问题,可以解决。它与您安装的Django版本有关,其中一些不被python 2.7支持。如果您使用pip安装了Django,则意味着您正在安装python 2.7可能不支持的最新版本,您可以在此处获取有关它的更多信息。我建议在安装过程中使用python 3或指定Django的版本(对于python 2.7为1.11)。

I had same problem and could solve it. It is related to the version of Django you’ve installed, some of them are not supported by python 2.7. If you have installed Django with pip, it means that you are installing the latest version of that which probably is not supported in python 2.7, You can get more information about it here. I would suggest to python 3 or specify the version of Django during installing (which is 1.11 for python 2.7).


回答 25

我解决了这个问题,以卸载Python的多个版本。查看Django官方文档,了解Python兼容性。

Python兼容性

Django 2.1支持Python 3.5、3.6和3.7。Django 2.0是支持Python 3.4的最新版本。”

manage.py文件

#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
   os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'work.settings')
   try:
       from django.core.management import execute_from_command_line
   except ImportError as exc:
      raise ImportError(
        "Couldn't import Django. Are you sure it's installed and "
        "available on your PYTHONPATH environment variable? Did you "
        "forget to activate a virtual environment?"
      ) from exc
    execute_from_command_line(sys.argv)

如果从此代码的第二行中删除“ from exc”,则由于多个版本的Python会产生另一个错误。

I solved this problem to uninstall the multiple version of Python. Check Django Official Documentation for Python compatibility.

Python compatibility

Django 2.1 supports Python 3.5, 3.6, and 3.7. Django 2.0 is the last version to support Python 3.4.”

manage.py file

#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
   os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'work.settings')
   try:
       from django.core.management import execute_from_command_line
   except ImportError as exc:
      raise ImportError(
        "Couldn't import Django. Are you sure it's installed and "
        "available on your PYTHONPATH environment variable? Did you "
        "forget to activate a virtual environment?"
      ) from exc
    execute_from_command_line(sys.argv)

If removing “from exc” from second last line of this code will generate another error due to multiple versions of Python.


回答 26

通过以下命令激活环境

  source  pathetoYourEnv/bin/activate

然后运行命令

python manage.py runserver

activate env by the Following Command

  source  pathetoYourEnv/bin/activate

then run command

python manage.py runserver

回答 27

您应该启动虚拟环境

怎么做?

首先使用终端cd进入包含manage.py的目录

然后输入 $source <myvenv>/bin/activate 用您的虚拟环境名称 replace,不带尖括号。

另一个问题可能是您的根目录和venv不匹配。结构应如下所示:

|-website
     ..facebook
     ..manage.py
     ..myvenv
     ..some other files

那是您的虚拟环境,manage.py应该在同一文件夹中。解决方案是重新启动项目。如果您遇到此错误,则必须尚未编写任何代码,因此请重新启动。

You should start your Virtual Environment,

how to do it?

first with terminal cd into the directory containing manage.py

then type $source <myvenv>/bin/activate replace with you Virtual Environment name, without angular brackets.

Another issue can that your root directory and venv mis-match. The structure should be something like this:

|-website
     ..facebook
     ..manage.py
     ..myvenv
     ..some other files

That is your virtual environment and manage.py should be in the same folder. Solution to that is to restart the project. If you are facing this error you must haven’t coded anything yet, so restart.


回答 28

当我使用以下方法激活虚拟环境时,也解决了我的问题:

source bin/activate

Solved my problem too when I activated my virtual environment using:

source bin/activate

回答 29

我遇到了这个问题(Mac),并按照下一页上的说明安装和激活虚拟环境

https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

$ cd [顶级django-project-dir]

$ python3 -m pip install –user virtualenv

$ python3 -m venv env

$ source env / bin / activate

安装并激活虚拟环境后,我对其进行了检查

$哪个Python

然后我将django安装到虚拟环境中

$ pip install django

然后我可以运行我的应用

$ python3 manage.py运行服务器

当我到达本教程的下一部分时

$ python manage.py startapp民意调查

我遇到了另一个错误:

     File "manage.py", line 16

   ) from exc
            ^

   SyntaxError: invalid syntax

我删除了

from exc

然后创建民意调查目录

I had this issue (Mac) and followed the instructions on the below page to install and activate the virtual environment

https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/

$ cd [ top-level-django-project-dir ]

$ python3 -m pip install –user virtualenv

$ python3 -m venv env

$ source env/bin/activate

Once I had installed and activated the virtual env I checked it

$ which python

Then I installed django into the virtual env

$ pip install django

And then I could run my app

$ python3 manage.py runserver

When I got to the next part of the tutorial

$ python manage.py startapp polls

I encountered another error:

     File "manage.py", line 16

   ) from exc
            ^

   SyntaxError: invalid syntax

I removed

from exc

and it then created the polls directory


如何更正TypeError:散列之前必须对Unicode对象进行编码?

问题:如何更正TypeError:散列之前必须对Unicode对象进行编码?

我有这个错误:

Traceback (most recent call last):
  File "python_md5_cracker.py", line 27, in <module>
  m.update(line)
TypeError: Unicode-objects must be encoded before hashing

当我尝试在Python 3.2.2中执行以下代码时:

import hashlib, sys
m = hashlib.md5()
hash = ""
hash_file = input("What is the file name in which the hash resides?  ")
wordlist = input("What is your wordlist?  (Enter the file name)  ")
try:
  hashdocument = open(hash_file, "r")
except IOError:
  print("Invalid file.")
  raw_input()
  sys.exit()
else:
  hash = hashdocument.readline()
  hash = hash.replace("\n", "")

try:
  wordlistfile = open(wordlist, "r")
except IOError:
  print("Invalid file.")
  raw_input()
  sys.exit()
else:
  pass
for line in wordlistfile:
  # Flush the buffer (this caused a massive problem when placed 
  # at the beginning of the script, because the buffer kept getting
  # overwritten, thus comparing incorrect hashes)
  m = hashlib.md5()
  line = line.replace("\n", "")
  m.update(line)
  word_hash = m.hexdigest()
  if word_hash == hash:
    print("Collision! The word corresponding to the given hash is", line)
    input()
    sys.exit()

print("The hash given does not correspond to any supplied word in the wordlist.")
input()
sys.exit()

I have this error:

Traceback (most recent call last):
  File "python_md5_cracker.py", line 27, in <module>
  m.update(line)
TypeError: Unicode-objects must be encoded before hashing

when I try to execute this code in Python 3.2.2:

import hashlib, sys
m = hashlib.md5()
hash = ""
hash_file = input("What is the file name in which the hash resides?  ")
wordlist = input("What is your wordlist?  (Enter the file name)  ")
try:
  hashdocument = open(hash_file, "r")
except IOError:
  print("Invalid file.")
  raw_input()
  sys.exit()
else:
  hash = hashdocument.readline()
  hash = hash.replace("\n", "")

try:
  wordlistfile = open(wordlist, "r")
except IOError:
  print("Invalid file.")
  raw_input()
  sys.exit()
else:
  pass
for line in wordlistfile:
  # Flush the buffer (this caused a massive problem when placed 
  # at the beginning of the script, because the buffer kept getting
  # overwritten, thus comparing incorrect hashes)
  m = hashlib.md5()
  line = line.replace("\n", "")
  m.update(line)
  word_hash = m.hexdigest()
  if word_hash == hash:
    print("Collision! The word corresponding to the given hash is", line)
    input()
    sys.exit()

print("The hash given does not correspond to any supplied word in the wordlist.")
input()
sys.exit()

回答 0

它可能正在寻找来自的字符编码wordlistfile

wordlistfile = open(wordlist,"r",encoding='utf-8')

或者,如果您逐行工作:

line.encode('utf-8')

It is probably looking for a character encoding from wordlistfile.

wordlistfile = open(wordlist,"r",encoding='utf-8')

Or, if you’re working on a line-by-line basis:

line.encode('utf-8')

回答 1

您必须定义encoding formatlike utf-8,尝试这种简单的方法,

本示例使用SHA256算法生成一个随机数:

>>> import hashlib
>>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f'

You must have to define encoding format like utf-8, Try this easy way,

This example generates a random number using the SHA256 algorithm:

>>> import hashlib
>>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f'

回答 2

要存储密码(PY3):

import hashlib, os
password_salt = os.urandom(32).hex()
password = '12345'

hash = hashlib.sha512()
hash.update(('%s%s' % (password_salt, password)).encode('utf-8'))
password_hash = hash.hexdigest()

To store the password (PY3):

import hashlib, os
password_salt = os.urandom(32).hex()
password = '12345'

hash = hashlib.sha512()
hash.update(('%s%s' % (password_salt, password)).encode('utf-8'))
password_hash = hash.hexdigest()

回答 3

该错误已说明您必须执行的操作。MD5对字节进行操作,因此您必须将Unicode字符串编码为bytes,例如使用line.encode('utf-8')

The error already says what you have to do. MD5 operates on bytes, so you have to encode Unicode string into bytes, e.g. with line.encode('utf-8').


回答 4

请首先查看答案。

现在,该错误信息是明确的:你只能使用字节,而不是Python字符串(曾经被认为是unicode在Python <3),所以你必须与你的首选编码编码字符串:utf-32utf-16utf-8或受限制的甚至是一个8-位编码(有些可能称为代码页)。

从文件中读取时,Python 3将自动将单词列表文件中的字节解码为Unicode。我建议你这样做:

m.update(line.encode(wordlistfile.encoding))

因此,推送到md5算法的编码数据的编码方式与基础文件完全相同。

Please take a look first at that answer.

Now, the error message is clear: you can only use bytes, not Python strings (what used to be unicode in Python < 3), so you have to encode the strings with your preferred encoding: utf-32, utf-16, utf-8 or even one of the restricted 8-bit encodings (what some might call codepages).

The bytes in your wordlist file are being automatically decoded to Unicode by Python 3 as you read from the file. I suggest you do:

m.update(line.encode(wordlistfile.encoding))

so that the encoded data pushed to the md5 algorithm are encoded exactly like the underlying file.


回答 5

import hashlib
string_to_hash = '123'
hash_object = hashlib.sha256(str(string_to_hash).encode('utf-8'))
print('Hash', hash_object.hexdigest())
import hashlib
string_to_hash = '123'
hash_object = hashlib.sha256(str(string_to_hash).encode('utf-8'))
print('Hash', hash_object.hexdigest())

回答 6

您可以以二进制模式打开文件:

import hashlib

with open(hash_file) as file:
    control_hash = file.readline().rstrip("\n")

wordlistfile = open(wordlist, "rb")
# ...
for line in wordlistfile:
    if hashlib.md5(line.rstrip(b'\n\r')).hexdigest() == control_hash:
       # collision

You could open the file in binary mode:

import hashlib

with open(hash_file) as file:
    control_hash = file.readline().rstrip("\n")

wordlistfile = open(wordlist, "rb")
# ...
for line in wordlistfile:
    if hashlib.md5(line.rstrip(b'\n\r')).hexdigest() == control_hash:
       # collision

回答 7

编码这行为我固定。

m.update(line.encode('utf-8'))

encoding this line fixed it for me.

m.update(line.encode('utf-8'))

回答 8

如果是单行字符串。用b或B包裹它。例如:

variable = b"This is a variable"

要么

variable2 = B"This is also a variable"

If it’s a single line string. wrapt it with b or B. e.g:

variable = b"This is a variable"

or

variable2 = B"This is also a variable"

回答 9

该程序是上述MD5破解程序的无错误和增强版本,该MD5破解程序读取包含哈希密码列表的文件,并根据英语词典单词列表中的哈希单词检查该文件。希望对您有所帮助。

我从以下链接https://github.com/dwyl/english-words下载了英语词典

# md5cracker.py
# English Dictionary https://github.com/dwyl/english-words 

import hashlib, sys

hash_file = 'exercise\hashed.txt'
wordlist = 'data_sets\english_dictionary\words.txt'

try:
    hashdocument = open(hash_file,'r')
except IOError:
    print('Invalid file.')
    sys.exit()
else:
    count = 0
    for hash in hashdocument:
        hash = hash.rstrip('\n')
        print(hash)
        i = 0
        with open(wordlist,'r') as wordlistfile:
            for word in wordlistfile:
                m = hashlib.md5()
                word = word.rstrip('\n')            
                m.update(word.encode('utf-8'))
                word_hash = m.hexdigest()
                if word_hash==hash:
                    print('The word, hash combination is ' + word + ',' + hash)
                    count += 1
                    break
                i += 1
        print('Itiration is ' + str(i))
    if count == 0:
        print('The hash given does not correspond to any supplied word in the wordlist.')
    else:
        print('Total passwords identified is: ' + str(count))
sys.exit()

This program is the bug free and enhanced version of the above MD5 cracker that reads the file containing list of hashed passwords and checks it against hashed word from the English dictionary word list. Hope it is helpful.

I downloaded the English dictionary from the following link https://github.com/dwyl/english-words

# md5cracker.py
# English Dictionary https://github.com/dwyl/english-words 

import hashlib, sys

hash_file = 'exercise\hashed.txt'
wordlist = 'data_sets\english_dictionary\words.txt'

try:
    hashdocument = open(hash_file,'r')
except IOError:
    print('Invalid file.')
    sys.exit()
else:
    count = 0
    for hash in hashdocument:
        hash = hash.rstrip('\n')
        print(hash)
        i = 0
        with open(wordlist,'r') as wordlistfile:
            for word in wordlistfile:
                m = hashlib.md5()
                word = word.rstrip('\n')            
                m.update(word.encode('utf-8'))
                word_hash = m.hexdigest()
                if word_hash==hash:
                    print('The word, hash combination is ' + word + ',' + hash)
                    count += 1
                    break
                i += 1
        print('Itiration is ' + str(i))
    if count == 0:
        print('The hash given does not correspond to any supplied word in the wordlist.')
    else:
        print('Total passwords identified is: ' + str(count))
sys.exit()

如何在Python中定义二维数组

问题:如何在Python中定义二维数组

我想定义一个没有初始化长度的二维数组,如下所示:

Matrix = [][]

但这不起作用…

我已经尝试过下面的代码,但是它也是错误的:

Matrix = [5][5]

错误:

Traceback ...

IndexError: list index out of range

我怎么了

I want to define a two-dimensional array without an initialized length like this:

Matrix = [][]

but it does not work…

I’ve tried the code below, but it is wrong too:

Matrix = [5][5]

Error:

Traceback ...

IndexError: list index out of range

What is my mistake?


回答 0

从技术上讲,您正在尝试索引未初始化的数组。您必须先使用列表初始化外部列表,然后再添加项目。Python将其称为“列表理解”。

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)] 

您现在可以将项目添加到列表中:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

请注意,矩阵是“ y”地址主地址,换句话说,“ y索引”位于“ x索引”之前。

print Matrix[0][0] # prints 1
x, y = 0, 6 
print Matrix[x][y] # prints 3; be careful with indexing! 

尽管您可以根据需要命名它们,但是如果您对内部列表和外部列表都使用“ x”,并且希望使用非平方矩阵,那么我会以这种方式来避免索引可能引起的混淆。

You’re technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this “list comprehension”.

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5;
Matrix = [[0 for x in range(w)] for y in range(h)] 

You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range... 
Matrix[0][6] = 3 # valid

Note that the matrix is “y” address major, in other words, the “y index” comes before the “x index”.

print Matrix[0][0] # prints 1
x, y = 0, 6 
print Matrix[x][y] # prints 3; be careful with indexing! 

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use “x” for both the inner and outer lists, and want a non-square Matrix.


回答 1

如果您确实需要矩阵,最好使用numpy。在numpy大多数情况下,矩阵运算使用具有二维的数组类型。有很多方法可以创建一个新数组。最有用的zeros函数之一是函数,它采用shape参数并返回给定形状的数组,其值初始化为零:

>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

这是创建二维数组和矩阵的其他一些方法(为了紧凑起见,删除了输出):

numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
numpy.empty((5, 5))                      # allocate, but don't initialize
numpy.ones((5, 5))                       # initialize with ones

numpy也提供了一种matrix类型,但是不再建议将其用于任何用途,以后可能会删除numpy它。

If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:

>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):

numpy.arange(25).reshape((5, 5))         # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5))   # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5))    # pass a Python list and reshape
numpy.empty((5, 5))                      # allocate, but don't initialize
numpy.ones((5, 5))                       # initialize with ones

numpy provides a matrix type as well, but it is no longer recommended for any use, and may be removed from numpy in the future.


回答 2

这是用于初始化列表列表的简短表示法:

matrix = [[0]*5 for i in range(5)]

不幸的是,将其缩短为类似的方法5*[5*[0]]实际上是行不通的,因为最终您会得到同一列表的5个副本,因此,当您修改其中一个副本时,它们都会更改,例如:

>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]

Here is a shorter notation for initializing a list of lists:

matrix = [[0]*5 for i in range(5)]

Unfortunately shortening this to something like 5*[5*[0]] doesn’t really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example:

>>> matrix = 5*[5*[0]]
>>> matrix
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix[4][4] = 2
>>> matrix
[[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]]

回答 3

如果要创建一个空矩阵,则正确的语法是

matrix = [[]]

如果您要生成大小为5的矩阵,并用0填充,

matrix = [[0 for i in xrange(5)] for i in xrange(5)]

If you want to create an empty matrix, the correct syntax is

matrix = [[]]

And if you want to generate a matrix of size 5 filled with 0,

matrix = [[0 for i in xrange(5)] for i in xrange(5)]

回答 4

如果只需要一个二维容器来容纳某些元素,则可以方便地使用字典:

Matrix = {}

然后,您可以执行以下操作:

Matrix[1,2] = 15
print Matrix[1,2]

这是有效的,因为它1,2是一个元组,并且您将其用作索引字典的键。结果类似于哑的稀疏矩阵。

如osa和Josap Valls所指出的,您也可以使用,Matrix = collections.defaultdict(lambda:0)以便丢失的元素具有默认值0

Vatsal进一步指出,该方法对于大型矩阵可能不是很有效,并且仅应在代码的非关键性能部分中使用。

If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:

Matrix = {}

Then you can do:

Matrix[1,2] = 15
print Matrix[1,2]

This works because 1,2 is a tuple, and you’re using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.

As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0) so that the missing elements have a default value of 0.

Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.


回答 5

在Python中,您将创建一个列表列表。您不必提前声明尺寸,但是可以声明。例如:

matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)

现在,matrix [0] [0] == 2和matrix [1] [0] ==3。您还可以使用列表理解语法。此示例两次使用它来构建“二维列表”:

from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]

In Python you will be creating a list of lists. You do not have to declare the dimensions ahead of time, but you can. For example:

matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)

Now matrix[0][0] == 2 and matrix[1][0] == 3. You can also use the list comprehension syntax. This example uses it twice over to build a “two-dimensional list”:

from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]

回答 6

公认的答案是正确且正确的,但是花了我一段时间才了解到我也可以使用它来创建一个完全空的数组。

l =  [[] for _ in range(3)]

结果是

[[], [], []]

The accepted answer is good and correct, but it took me a while to understand that I could also use it to create a completely empty array.

l =  [[] for _ in range(3)]

results in

[[], [], []]

回答 7

您应该列出列表,最好的方法是使用嵌套的理解:

>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

在您的[5][5]示例中,您正在创建一个内部带有整数“ 5”的列表,并尝试访问其第五项,这自然会引发IndexError,因为没有第五项:

>>> l = [5]
>>> l[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

You should make a list of lists, and the best way is to use nested comprehensions:

>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

On your [5][5] example, you are creating a list with an integer “5” inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:

>>> l = [5]
>>> l[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

回答 8

rows = int(input())
cols = int(input())

matrix = []
for i in range(rows):
  row = []
  for j in range(cols):
    row.append(0)
  matrix.append(row)

print(matrix)

为什么这么长的代码,Python您也会问?

很久以前,当我不熟悉Python时,我看到了编写2D矩阵的单行答案,并告诉自己我不再打算在Python中再次使用2D矩阵。(这些行很吓人,它没有给我有关Python所做的任何信息。还要注意,我不知道这些速记法。)

无论如何,这是一个来自C,CPP和Java背景的初学者的代码

给Python爱好者和专家的说明:请不要因为我编写了详细的代码而投了反对票。

rows = int(input())
cols = int(input())

matrix = []
for i in range(rows):
  row = []
  for j in range(cols):
    row.append(0)
  matrix.append(row)

print(matrix)

Why such a long code, that too in Python you ask?

Long back when I was not comfortable with Python, I saw the single line answers for writing 2D matrix and told myself I am not going to use 2-D matrix in Python again. (Those single lines were pretty scary and It didn’t give me any information on what Python was doing. Also note that I am not aware of these shorthands.)

Anyways, here’s the code for a beginner whose coming from C, CPP and Java background

Note to Python Lovers and Experts: Please do not down vote just because I wrote a detailed code.


回答 9

重写以便于阅读:

# 2D array/ matrix

# 5 rows, 5 cols
rows_count = 5
cols_count = 5

# create
#     creation looks reverse
#     create an array of "cols_count" cols, for each of the "rows_count" rows
#        all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]

# index is from 0 to 4
#     for both rows & cols
#     since 5 rows, 5 cols

# use
two_d_array[0][0] = 1
print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)

two_d_array[1][0] = 2
print two_d_array[1][0]  # prints 2   # 2nd row, 1st col

two_d_array[1][4] = 3
print two_d_array[1][4]  # prints 3   # 2nd row, last col

two_d_array[4][4] = 4
print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)

A rewrite for easy reading:

# 2D array/ matrix

# 5 rows, 5 cols
rows_count = 5
cols_count = 5

# create
#     creation looks reverse
#     create an array of "cols_count" cols, for each of the "rows_count" rows
#        all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]

# index is from 0 to 4
#     for both rows & cols
#     since 5 rows, 5 cols

# use
two_d_array[0][0] = 1
print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)

two_d_array[1][0] = 2
print two_d_array[1][0]  # prints 2   # 2nd row, 1st col

two_d_array[1][4] = 3
print two_d_array[1][4]  # prints 3   # 2nd row, last col

two_d_array[4][4] = 4
print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)

回答 10

采用:

matrix = [[0]*5 for i in range(5)]

第一维的* 5起作用是因为在此级别上,数据是不可变的。

Use:

matrix = [[0]*5 for i in range(5)]

The *5 for the first dimension works because at this level the data is immutable.


回答 11

声明零(一)矩阵:

numpy.zeros((x, y))

例如

>>> numpy.zeros((3, 5))
    array([[ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.]])

或numpy.ones((x,y))例如

>>> np.ones((3, 5))
array([[ 1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.]])

甚至三个尺寸都是可能的。(http://www.astro.ufl.edu/~warner/prog/python.html参见->多维数组)

To declare a matrix of zeros (ones):

numpy.zeros((x, y))

e.g.

>>> numpy.zeros((3, 5))
    array([[ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.]])

or numpy.ones((x, y)) e.g.

>>> np.ones((3, 5))
array([[ 1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.],
   [ 1.,  1.,  1.,  1.,  1.]])

Even three dimensions are possible. (http://www.astro.ufl.edu/~warner/prog/python.html see –> Multi-dimensional arrays)


回答 12

这就是我通常在python中创建2D数组的方式。

col = 3
row = 4
array = [[0] * col for _ in range(row)]

与在列表理解中使用两个for循环相比,我发现此语法易于记住。

This is how I usually create 2D arrays in python.

col = 3
row = 4
array = [[0] * col for _ in range(row)]

I find this syntax easy to remember compared to using two for loops in a list comprehension.


回答 13

我正在使用我的第一个Python脚本,我对方矩阵示例有些困惑,因此希望以下示例可以帮助您节省一些时间:

 # Creates a 2 x 5 matrix
 Matrix = [[0 for y in xrange(5)] for x in xrange(2)]

以便

Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range

I’m on my first Python script, and I was a little confused by the square matrix example so I hope the below example will help you save some time:

 # Creates a 2 x 5 matrix
 Matrix = [[0 for y in xrange(5)] for x in xrange(2)]

so that

Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range

回答 14

使用NumPy,您可以像这样初始化空矩阵:

import numpy as np
mm = np.matrix([])

然后像这样追加数据:

mm = np.append(mm, [[1,2]], axis=1)

Using NumPy you can initialize empty matrix like this:

import numpy as np
mm = np.matrix([])

And later append data like this:

mm = np.append(mm, [[1,2]], axis=1)

回答 15

我读了这样的逗号分隔文件:

data=[]
for l in infile:
    l = split(',')
    data.append(l)

然后,列表“数据”是带有索引数据的列表的列表[行] [列]

I read in comma separated files like this:

data=[]
for l in infile:
    l = split(',')
    data.append(l)

The list “data” is then a list of lists with index data[row][col]


回答 16

如果您希望能够将其视为2D数组,而不是被迫以列表列表的方式思考(我认为这自然得多),则可以执行以下操作:

import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()

结果是一个列表(不是NumPy数组),您可以用数字,字符串或其他内容覆盖各个位置。

If you want to be able to think it as a 2D array rather than being forced to think in term of a list of lists (much more natural in my opinion), you can do the following:

import numpy
Nx=3; Ny=4
my2Dlist= numpy.zeros((Nx,Ny)).tolist()

The result is a list (not a NumPy array), and you can overwrite the individual positions with numbers, strings, whatever.


回答 17

这就是字典的用途!

matrix = {}

您可以通过两种方式定义

matrix[0,0] = value

要么

matrix = { (0,0)  : value }

结果:

   [ value,  value,  value,  value,  value],
   [ value,  value,  value,  value,  value],
   ...

That’s what dictionary is made for!

matrix = {}

You can define keys and values in two ways:

matrix[0,0] = value

or

matrix = { (0,0)  : value }

Result:

   [ value,  value,  value,  value,  value],
   [ value,  value,  value,  value,  value],
   ...

回答 18

采用:

import copy

def ndlist(*args, init=0):
    dp = init
    for x in reversed(args):
        dp = [copy.deepcopy(dp) for _ in range(x)]
    return dp

l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1

我确实认为NumPy是要走的路。如果您不想使用NumPy,则以上是一种通用方法。

Use:

import copy

def ndlist(*args, init=0):
    dp = init
    for x in reversed(args):
        dp = [copy.deepcopy(dp) for _ in range(x)]
    return dp

l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1

I do think NumPy is the way to go. The above is a generic one if you don’t want to use NumPy.


回答 19

通过使用列表:

matrix_in_python  = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]

通过使用dict:您还可以将此信息存储在哈希表中,以进行快速搜索,例如

matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};

matrix [‘1’]将为您提供O(1)时间的结果

* nb:您需要处理哈希表中的冲突

by using list :

matrix_in_python  = [['Roy',80,75,85,90,95],['John',75,80,75,85,100],['Dave',80,80,80,90,95]]

by using dict: you can also store this info in the hash table for fast searching like

matrix = { '1':[0,0] , '2':[0,1],'3':[0,2],'4' : [1,0],'5':[1,1],'6':[1,2],'7':[2,0],'8':[2,1],'9':[2,2]};

matrix[‘1’] will give you result in O(1) time

*nb: you need to deal with a collision in the hash table


回答 20

如果在开始之前没有尺寸信息,请创建两个一维列表。

list 1: To store rows
list 2: Actual two-dimensional matrix

将整个行存储在第一个列表中。完成后,将列表1附加到列表2:

from random import randint

coordinates=[]
temp=[]
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
    randomx=randint(0,1000)
    randomy=randint(0,1000)
    temp=[]
    temp.append(randomx)
    temp.append(randomy)
    coordinates.append(temp)

print coordinates

输出:

Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]

If you don’t have size information before start then create two one-dimensional lists.

list 1: To store rows
list 2: Actual two-dimensional matrix

Store the entire row in the 1st list. Once done, append list 1 into list 2:

from random import randint

coordinates=[]
temp=[]
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
    randomx=randint(0,1000)
    randomy=randint(0,1000)
    temp=[]
    temp.append(randomx)
    temp.append(randomy)
    coordinates.append(temp)

print coordinates

Output:

Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]

回答 21

# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5

请注意此简短表达,请参见@FJ答案中的完整解释

# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5

Be careful about this short expression, see full explanation down in @F.J’s answer


回答 22

l=[[0]*(L) for _ in range(W)]

将比:

l = [[0 for x in range(L)] for y in range(W)] 
l=[[0]*(L) for _ in range(W)]

Will be faster than:

l = [[0 for x in range(L)] for y in range(W)] 

回答 23

您可以通过将两个或多个方括号或第三个方括号([]用逗号分隔)嵌套在一起来创建一个空的二维列表,如下所示:

Matrix = [[], []]

现在假设您要在Matrix[0][0]其后附加1,然后键入:

Matrix[0].append(1)

现在,键入Matrix并按Enter。输出将是:

[[1], []]

You can create an empty two dimensional list by nesting two or more square bracing or third bracket ([], separated by comma) with a square bracing, just like below:

Matrix = [[], []]

Now suppose you want to append 1 to Matrix[0][0] then you type:

Matrix[0].append(1)

Now, type Matrix and hit Enter. The output will be:

[[1], []]

回答 24

尝试这个:

rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
    my_list.append(list(map(int, input().split())))

Try this:

rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
    my_list.append(list(map(int, input().split())))

回答 25

如果您需要带有预定义数字的矩阵,则可以使用以下代码:

def matrix(rows, cols, start=0):
    return [[c + start + r * cols for c in range(cols)] for r in range(rows)]


assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]

In case if you need a matrix with predefined numbers you can use the following code:

def matrix(rows, cols, start=0):
    return [[c + start + r * cols for c in range(cols)] for r in range(rows)]


assert matrix(2, 3, 1) == [[1, 2, 3], [4, 5, 6]]

回答 26

这是在python中创建矩阵的代码片段:

# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))

# initialize the list
l=[[0]*cols for i in range(rows)]

# fill some random values in it
for i in range(0,rows):
    for j in range(0,cols):
        l[i][j] = i+j

# print the list
for i in range(0,rows):
    print()
    for j in range(0,cols):
        print(l[i][j],end=" ")

如果我错过了什么,请提出建议。

Here is the code snippet for creating a matrix in python:

# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))

# initialize the list
l=[[0]*cols for i in range(rows)]

# fill some random values in it
for i in range(0,rows):
    for j in range(0,cols):
        l[i][j] = i+j

# print the list
for i in range(0,rows):
    print()
    for j in range(0,cols):
        print(l[i][j],end=" ")

Please suggest if I have missed something.