标签归档:loops

为什么从__future__ import print_function使用会破坏Python2样式的打印?[关闭]

问题:为什么从__future__ import print_function使用会破坏Python2样式的打印?[关闭]

我是使用python编程的新手,但我尝试使用分隔符并结束打印,但这仍然给我带来语法错误。

我正在使用python 2.7。

这是我的代码:

from __future__ import print_function
import sys, os, time

for x in range(0,10):
    print x, sep=' ', end=''
    time.sleep(1)

这是错误:

$ python2 xy.py
  File "xy.py", line 5
    print x, sep=' ', end=''
          ^
SyntaxError: invalid syntax
$

I am new at programming with python, and I am trying to print out with a separator and end but it is still giving me a syntax error.

I am using python 2.7.

Here is my code:

from __future__ import print_function
import sys, os, time

for x in range(0,10):
    print x, sep=' ', end=''
    time.sleep(1)

And here is the error:

$ python2 xy.py
  File "xy.py", line 5
    print x, sep=' ', end=''
          ^
SyntaxError: invalid syntax
$

回答 0

首先,from __future__ import print_function必须是脚本中的第一行代码(除了下面提到的一些exceptions)。第二,正如其他答案所说,您现在必须print用作函数。这就是重点from __future__ import print_function;将print 功能从Python 3带入Python 2.6+。

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__语句必须位于文件的顶部,因为它们会更改语言的基本内容,因此编译器需要从一开始就了解它们。从文档中

将来的语句在编译时会得到特殊识别和处理:更改核心结构的语义通常是通过生成不同的代码来实现的。甚至可能是新功能引入了新的不兼容语法(例如新的保留字)的情况,在这种情况下,编译器可能需要以不同的方式解析模块。直到运行时才能推迟此类决策。

该文档还提到,__future__语句之前唯一可以做的事情就是模块文档字符串,注释,空白行和其他将来的语句。

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That’s the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.


如何为列表中的每个元素添加一个整数?

问题:如何为列表中的每个元素添加一个整数?

如果我有list=[1,2,3]并且想要添加1到每个元素以获取输出[2,3,4],我该怎么做?

我假设我会使用for循环,但不确定具体如何。

If I have list=[1,2,3] and I want to add 1 to each element to get the output [2,3,4], how would I do that?

I assume I would use a for loop but not sure exactly how.


回答 0

new_list = [x+1 for x in my_list]
new_list = [x+1 for x in my_list]

回答 1

>>> mylist = [1,2,3]
>>> [x+1 for x in mylist]
[2, 3, 4]
>>>

list-comprehensions python

>>> mylist = [1,2,3]
>>> [x+1 for x in mylist]
[2, 3, 4]
>>>

list-comprehensions python.


回答 2

列表理解中的其他答案可能是简单加法的最佳选择,但是如果您有一个更复杂的函数需要将其应用于所有元素,则可以进行映射可能是一个不错的选择。

在您的示例中,它将是:

>>> map(lambda x:x+1, [1,2,3])
[2,3,4]

The other answers on list comprehension are probably the best bet for simple addition, but if you have a more complex function that you needed to apply to all the elements then map may be a good fit.

In your example it would be:

>>> map(lambda x:x+1, [1,2,3])
[2,3,4]

回答 3

如果要使用numpy,则还有另一种方法,如下所示

import numpy as np
list1 = [1,2,3]
list1 = list(np.asarray(list1) + 1)

if you want to use numpy there is another method as follows

import numpy as np
list1 = [1,2,3]
list1 = list(np.asarray(list1) + 1)

回答 4

编辑:这不是就地

首先,不要在变量中使用单词“列表”。它遮盖了关键字list

最好的方法是使用拼接来完成它,请注意[:]表示拼接:

>>> _list=[1,2,3]
>>> _list[:]=[i+1 for i in _list]
>>> _list
[2, 3, 4]

Edit: this isn’t in-place

Firstly don’t use the word ‘list’ for your variable. It shadows the keyword list.

The best way is to do it in place using splicing, note the [:] denotes a splice:

>>> _list=[1,2,3]
>>> _list[:]=[i+1 for i in _list]
>>> _list
[2, 3, 4]

回答 5

>>> [x.__add__(1) for x in [1, 3, 5]]
3: [2, 4, 6]

我的目的是要揭示列表中的项目是否为整数,它支持各种内置函数。

>>> [x.__add__(1) for x in [1, 3, 5]]
3: [2, 4, 6]

My intention here is to expose if the item in the list is an integer it supports various built-in functions.


回答 6

Python 2+:

>>> mylist = [1,2,3]
>>> map(lambda x: x + 1, mylist)
[2, 3, 4]

Python 3+:

>>> mylist = [1,2,3]
>>> list(map(lambda x: x + 1, mylist))
[2, 3, 4]

Python 2+:

>>> mylist = [1,2,3]
>>> map(lambda x: x + 1, mylist)
[2, 3, 4]

Python 3+:

>>> mylist = [1,2,3]
>>> list(map(lambda x: x + 1, mylist))
[2, 3, 4]

回答 7

import numpy as np

np.add([1, 2, 3], 1).tolist()

这使

[2, 3, 4]
import numpy as np

np.add([1, 2, 3], 1).tolist()

which gives

[2, 3, 4]

回答 8

遇到了一种效率不高但独特的方法。因此可以共享它,是的,它需要额外的空间来存储另一个列表。

from operator import add
test_list1 = [4, 5, 6, 2, 10]
test_list2 = [1] * len(test_list1)

res_list = list(map(add, test_list1, test_list2))

print(test_list1)
print(test_list2)
print(res_list)

#### Output ####
[4, 5, 6, 2, 10]
[1, 1, 1, 1, 1]
[5, 6, 7, 3, 11]

Came across a not so efficient, but unique way of doing it. So sharing it across.And yes it requires extra space for another list.

from operator import add
test_list1 = [4, 5, 6, 2, 10]
test_list2 = [1] * len(test_list1)

res_list = list(map(add, test_list1, test_list2))

print(test_list1)
print(test_list2)
print(res_list)

#### Output ####
[4, 5, 6, 2, 10]
[1, 1, 1, 1, 1]
[5, 6, 7, 3, 11]

回答 9

list = [1,2,3,4,5]

for index in range(5):
      list[index] = list[index] +1

print(list)
list = [1,2,3,4,5]

for index in range(len(list)):
      list[index] = list[index] +1

print(list)

回答 10

上面的许多答案都很好。我也看到了一些奇怪的答案,可以胜任这项工作。另外,最后看到的答案是通过正常循环。这种愿意给出答案的意愿将我引向itertoolsnumpy,它们将以不同的方式完成相同的工作。

在这里,我介绍了完成此工作的不同方法,以上未作回答。

import operator
import itertools

x = [3, 5, 6, 7]

integer = 89

"""
Want more vairaint can also use zip_longest from itertools instead just zip
"""
#lazy eval
a = itertools.starmap(operator.add, zip(x, [89] * len(x))) # this is not subscriptable but iterable
print(a)
for i in a:
  print(i, end = ",")


# prepared list
a = list(itertools.starmap(operator.add, zip(x, [89] * len(x)))) # this returns list
print(a)



# With numpy (before this, install numpy if not present with `pip install numpy`)
import numpy

res = numpy.ones(len(x), dtype=int) * integer + x # it returns numpy array
res = numpy.array(x) + integer # you can also use this, infact there are many ways to play around
print(res)
print(res.shape) # prints structure of array, i.e. shape

# if you specifically want a list, then use tolist

res_list = res.tolist()
print(res_list)

输出量

>>> <itertools.starmap object at 0x0000028793490AF0> # output by lazy val
>>> 92,94,95,96,                                     # output of iterating above starmap object
>>> [92, 94, 95, 96]                                 # output obtained by casting to list
>>>                   __
>>> # |\ | |  | |\/| |__| \ /
>>> # | \| |__| |  | |     |
>>> [92 94 95 96]                                    # this is numpy.ndarray object
>>> (4,)                                             # shape of array
>>> [92, 94, 95, 96]                                 # this is a list object (doesn't have a shape)

唯一强调使用numpy是,应该始终对numpy之类的库进行此类操作,因为它对于大型数组而言性能高效。

Many of the answers above are very good. I’ve also seen some weird answers that will do the job. Also, the last answer seen was through a normal loop. This willingness to give answers leads me to itertools and numpy, which will do the same job in a different way.

Here I present different ways to do the job, not answered above.

import operator
import itertools

x = [3, 5, 6, 7]

integer = 89

"""
Want more vairaint can also use zip_longest from itertools instead just zip
"""
#lazy eval
a = itertools.starmap(operator.add, zip(x, [89] * len(x))) # this is not subscriptable but iterable
print(a)
for i in a:
  print(i, end = ",")


# prepared list
a = list(itertools.starmap(operator.add, zip(x, [89] * len(x)))) # this returns list
print(a)



# With numpy (before this, install numpy if not present with `pip install numpy`)
import numpy

res = numpy.ones(len(x), dtype=int) * integer + x # it returns numpy array
res = numpy.array(x) + integer # you can also use this, infact there are many ways to play around
print(res)
print(res.shape) # prints structure of array, i.e. shape

# if you specifically want a list, then use tolist

res_list = res.tolist()
print(res_list)

Output

>>> <itertools.starmap object at 0x0000028793490AF0> # output by lazy val
>>> 92,94,95,96,                                     # output of iterating above starmap object
>>> [92, 94, 95, 96]                                 # output obtained by casting to list
>>>                   __
>>> # |\ | |  | |\/| |__| \ /
>>> # | \| |__| |  | |     |
>>> [92 94 95 96]                                    # this is numpy.ndarray object
>>> (4,)                                             # shape of array
>>> [92, 94, 95, 96]                                 # this is a list object (doesn't have a shape)

My sole reason to highlight the use of numpy is that one should always do such manipulations with libraries like numpy because it is performance efficient for very large arrays.


Python:继续外循环中的下一个迭代

问题:Python:继续外循环中的下一个迭代

我想知道是否有任何内置方法可以继续进行python外循环中的下一次迭代。例如,考虑以下代码:

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            continue
    ...block1...

我希望此继续语句退出jj循环并转到ii循环中的下一项。我可以通过其他方式(通过设置标志变量)来实现此逻辑,但是有没有简单的方法可以做到这一点,或者这就像要求太多吗?

I wanted to know if there are any built-in ways to continue to next iteration in outer loop in python. For example, consider the code:

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            continue
    ...block1...

I want this continue statement to exit the jj loop and goto next item in the ii loop. I can implement this logic in some other way (by setting a flag variable), but is there an easy way to do this, or is this like asking for too much?


回答 0

for i in ...:
    for j in ...:
        for k in ...:
            if something:
                # continue loop i

在一般情况下,当您有多个循环级别且break对您不起作用时(因为您要继续上一个循环,而不是当前循环的右上循环),可以执行以下操作之一

将您想转义的循环重构为一个函数

def inner():
    for j in ...:
        for k in ...:
            if something:
                return


for i in ...:
    inner()

缺点是您可能需要将以前在范围内的一些变量传递给该新函数。您既可以将它们作为参数传递,也可以在对象上使它们成为实例变量(如果有意义,仅为此函数创建一个新对象),或者全局变量,单例(无论是什么)(ehm,ehm)。

或者,您可以将其定义inner为嵌套函数,然后使其仅捕获所需的内容(可能会更慢?)

for i in ...:
    def inner():
        for j in ...:
            for k in ...:
                if something:
                    return
    inner()

使用exceptions

从哲学上讲,这就是exceptions,在必要时,通过结构化的编程构建块(如果是,为时,为时)中断程序流。

这样做的好处是您不必将单个代码分成多个部分。如果这是您在用Python编写代码时正在设计的某种计算,那么这很好。在早期引入抽象可能会使您减速。

这种方法的坏处在于,解释器/编译器作者通常会认为异常是exceptions情况,因此会相应地对其进行优化。

class ContinueI(Exception):
    pass


continue_i = ContinueI()

for i in ...:
    try:
        for j in ...:
            for k in ...:
                if something:
                    raise continue_i
    except ContinueI:
        continue

为此创建一个特殊的异常类,这样您就不会冒意外地使某些其他异常消失的风险。

完全其他的东西

我相信还有其他解决方案。

for i in ...:
    for j in ...:
        for k in ...:
            if something:
                # continue loop i

In a general case, when you have multiple levels of looping and break does not work for you (because you want to continue one of the upper loops, not the one right above the current one), you can do one of the following

Refactor the loops you want to escape from into a function

def inner():
    for j in ...:
        for k in ...:
            if something:
                return


for i in ...:
    inner()

The disadvantage is that you may need to pass to that new function some variables, which were previously in scope. You can either just pass them as parameters, make them instance variables on an object (create a new object just for this function, if it makes sense), or global variables, singletons, whatever (ehm, ehm).

Or you can define inner as a nested function and let it just capture what it needs (may be slower?)

for i in ...:
    def inner():
        for j in ...:
            for k in ...:
                if something:
                    return
    inner()

Use exceptions

Philosophically, this is what exceptions are for, breaking the program flow through the structured programming building blocks (if, for, while) when necessary.

The advantage is that you don’t have to break the single piece of code into multiple parts. This is good if it is some kind of computation that you are designing while writing it in Python. Introducing abstractions at this early point may slow you down.

Bad thing with this approach is that interpreter/compiler authors usually assume that exceptions are exceptional and optimize for them accordingly.

class ContinueI(Exception):
    pass


continue_i = ContinueI()

for i in ...:
    try:
        for j in ...:
            for k in ...:
                if something:
                    raise continue_i
    except ContinueI:
        continue

Create a special exception class for this, so that you don’t risk accidentally silencing some other exception.

Something else entirely

I am sure there are still other solutions.


回答 1

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            break
    else:
        ...block1...

Break 将中断内部循环,并且不会执行block1(仅在内部循环正常退出时才会运行)。

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            break
    else:
        ...block1...

Break will break the inner loop, and block1 won’t be executed (it will run only if the inner loop is exited normally).


回答 2

在其他语言中,您可以标记循环并从标记循环中中断。 Python增强提案(PEP)3136建议将它们添加到Python中,Guido拒绝了它

但是,我拒绝这样的理由是,如此复杂的代码很少需要此功能。在大多数情况下,现有的变通办法可以生成干净的代码,例如使用“返回”。虽然我确信在某些(罕见)实际情况下,代码的清晰性会受到重构的影响,从而可以使用return,但是这被两个问题抵消了:

  1. 复杂性永久地增加了语言。这不仅会影响所有Python实现,而且会影响每个源代码分析工具,当然还会影响该语言的所有文档。

  2. 我期望该功能的滥用程度将超过其正确使用的程度,从而导致代码清晰度净下降(此后对所有编写的Python代码进行衡量)。懒惰的程序员无处不在,在您不了解它之前,您就难以理解难以理解的代码。

因此,如果那是您希望自己没有运气的原因,请查看其他答案之一,因为那里有不错的选择。

In other languages you can label the loop and break from the labelled loop. Python Enhancement Proposal (PEP) 3136 suggested adding these to Python but Guido rejected it:

However, I’m rejecting it on the basis that code so complicated to require this feature is very rare. In most cases there are existing work-arounds that produce clean code, for example using ‘return’. While I’m sure there are some (rare) real cases where clarity of the code would suffer from a refactoring that makes it possible to use return, this is offset by two issues:

  1. The complexity added to the language, permanently. This affects not only all Python implementations, but also every source analysis tool, plus of course all documentation for the language.

  2. My expectation that the feature will be abused more than it will be used right, leading to a net decrease in code clarity (measured across all Python code written henceforth). Lazy programmers are everywhere, and before you know it you have an incredible mess on your hands of unintelligible code.

So if that’s what you were hoping for you’re out of luck, but look at one of the other answers as there are good options there.


回答 3

我认为您可以执行以下操作:

for ii in range(200):
    restart = False
    for jj in range(200, 400):
        ...block0...
        if something:
            restart = True
            break
    if restart:
        continue
    ...block1...

I think you could do something like this:

for ii in range(200):
    restart = False
    for jj in range(200, 400):
        ...block0...
        if something:
            restart = True
            break
    if restart:
        continue
    ...block1...

回答 4

我认为最简单的方法之一是用“ break”语句代替“ continue”,即

for ii in range(200):
 for jj in range(200, 400):
    ...block0...
    if something:
        break
 ...block1...       

例如,以下是简单的代码,可查看其运行的确切情况:

for i in range(10):
    print("doing outer loop")
    print("i=",i)
    for p in range(10):
        print("doing inner loop")
        print("p=",p)
        if p==3:
            print("breaking from inner loop")
            break
    print("doing some code in outer loop")

I think one of the easiest ways to achieve this is to replace “continue” with “break” statement,i.e.

for ii in range(200):
 for jj in range(200, 400):
    ...block0...
    if something:
        break
 ...block1...       

For example, here is the easy code to see how exactly it goes on:

for i in range(10):
    print("doing outer loop")
    print("i=",i)
    for p in range(10):
        print("doing inner loop")
        print("p=",p)
        if p==3:
            print("breaking from inner loop")
            break
    print("doing some code in outer loop")

回答 5

解决此类问题的另一种方法是使用Exception()。

for ii in range(200):
    try:
        for jj in range(200, 400):
            ...block0...
            if something:
                raise Exception()
    except Exception:
        continue
    ...block1...

例如:

for n in range(1,4):
    for m in range(1,4):
        print n,'-',m

结果:

    1-1
    1-2
    1-3
    2-1
    2-2
    2-3
    3-1
    3-2
    3-3

假设如果m = 3,我们想从m循环跳转到外部n循环:

for n in range(1,4):
    try:
        for m in range(1,4):
            if m == 3:
                raise Exception()            
            print n,'-',m
    except Exception:
        continue

结果:

    1-1
    1-2
    2-1
    2-2
    3-1
    3-2

参考链接:http : //www.programming-idioms.org/idiom/42/continue-outer-loop/1264/python

Another way to deal with this kind of problem is to use Exception().

for ii in range(200):
    try:
        for jj in range(200, 400):
            ...block0...
            if something:
                raise Exception()
    except Exception:
        continue
    ...block1...

For example:

for n in range(1,4):
    for m in range(1,4):
        print n,'-',m

result:

    1-1
    1-2
    1-3
    2-1
    2-2
    2-3
    3-1
    3-2
    3-3

Assuming we want to jump to the outer n loop from m loop if m =3:

for n in range(1,4):
    try:
        for m in range(1,4):
            if m == 3:
                raise Exception()            
            print n,'-',m
    except Exception:
        continue

result:

    1-1
    1-2
    2-1
    2-2
    3-1
    3-2

Reference link:http://www.programming-idioms.org/idiom/42/continue-outer-loop/1264/python


回答 6

我们想找到一些东西,然后停止内部迭代。我使用标志系统。

for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False

We want to find something and then stop the inner iteration. I use a flag system.

for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False

回答 7

我只是做了这样的事情。我对此的解决方案是用列表理解替换内部for循环。

for ii in range(200):
    done = any([op(ii, jj) for jj in range(200, 400)])
    ...block0...
    if done:
        continue
    ...block1...

其中op是作用于ii和jj组合的布尔运算符。就我而言,如果任何操作返回true,我就完成了。

这实际上与将代码分解为一个函数没有什么不同,但是我认为使用“ any”运算符对布尔值列表进行逻辑或,然后全部执行逻辑是很有趣的。它还避免了函数调用。

I just did something like this. My solution for this was to replace the interior for loop with a list comprehension.

for ii in range(200):
    done = any([op(ii, jj) for jj in range(200, 400)])
    ...block0...
    if done:
        continue
    ...block1...

where op is some boolean operator acting on a combination of ii and jj. In my case, if any of the operations returned true, I was done.

This is really not that different from breaking the code out into a function, but I thought that using the “any” operator to do a logical OR on a list of booleans and doing the logic all in one line was interesting. It also avoids the function call.


迭代对应于Python中列表的字典键值

问题:迭代对应于Python中列表的字典键值

使用Python 2.7。我有一本字典,其中以球队名称为关键,对每支球队得分并允许的奔跑次数作为值列表:

NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]}

我希望能够将字典提供给函数并遍历每个团队(键)。

这是我正在使用的代码。现在,我只能逐队参加。我将如何遍历每个团队并为每个团队打印预期的win_percentage?

def Pythag(league):
    runs_scored = float(league['Phillies'][0])
    runs_allowed = float(league['Phillies'][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

谢谢你的帮助。

Working in Python 2.7. I have a dictionary with team names as the keys and the amount of runs scored and allowed for each team as the value list:

NL_East = {'Phillies': [645, 469], 'Braves': [599, 548], 'Mets': [653, 672]}

I would like to be able to feed the dictionary into a function and iterate over each team (the keys).

Here’s the code I’m using. Right now, I can only go team by team. How would I iterate over each team and print the expected win_percentage for each team?

def Pythag(league):
    runs_scored = float(league['Phillies'][0])
    runs_allowed = float(league['Phillies'][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

Thanks for any help.


回答 0

您有几种选择可以遍历字典。

如果迭代字典本身(for team in league),则将迭代字典的键。当使用for循环进行循环时,无论您是在dict(league)本身上循环还是在以下情况下,行为都是相同的league.keys()

for team in league.keys():
    runs_scored, runs_allowed = map(float, league[team])

您还可以通过迭代遍历键和值一次league.items()

for team, runs in league.items():
    runs_scored, runs_allowed = map(float, runs)

您甚至可以在迭代时执行元组拆包:

for team, (runs_scored, runs_allowed) in league.items():
    runs_scored = float(runs_scored)
    runs_allowed = float(runs_allowed)

You have several options for iterating over a dictionary.

If you iterate over the dictionary itself (for team in league), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league) itself, or league.keys():

for team in league.keys():
    runs_scored, runs_allowed = map(float, league[team])

You can also iterate over both the keys and the values at once by iterating over league.items():

for team, runs in league.items():
    runs_scored, runs_allowed = map(float, runs)

You can even perform your tuple unpacking while iterating:

for team, (runs_scored, runs_allowed) in league.items():
    runs_scored = float(runs_scored)
    runs_allowed = float(runs_allowed)

回答 1

您也可以很容易地遍历字典:

for team, scores in NL_East.iteritems():
    runs_scored = float(scores[0])
    runs_allowed = float(scores[1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print '%s: %.1f%%' % (team, win_percentage)

You can very easily iterate over dictionaries, too:

for team, scores in NL_East.iteritems():
    runs_scored = float(scores[0])
    runs_allowed = float(scores[1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print '%s: %.1f%%' % (team, win_percentage)

回答 2

字典具有一个称为的内置函数iterkeys()

尝试:

for team in league.iterkeys():
    runs_scored = float(league[team][0])
    runs_allowed = float(league[team][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

Dictionaries have a built in function called iterkeys().

Try:

for team in league.iterkeys():
    runs_scored = float(league[team][0])
    runs_allowed = float(league[team][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

回答 3

字典对象允许您迭代其项目。此外,通过模式匹配和__future__可以使事情稍微简化。

最后,您可以将逻辑从打印中分离出来,以使事情在以后的重构/调试中更加容易。

from __future__ import division

def Pythag(league):
    def win_percentages():
        for team, (runs_scored, runs_allowed) in league.iteritems():
            win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
            yield win_percentage

    for win_percentage in win_percentages():
        print win_percentage

Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__ you can do simplify things a bit.

Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.

from __future__ import division

def Pythag(league):
    def win_percentages():
        for team, (runs_scored, runs_allowed) in league.iteritems():
            win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
            yield win_percentage

    for win_percentage in win_percentages():
        print win_percentage

回答 4

列表理解可以缩短内容…

win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]

List comprehension can shorten things…

win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]

在Python中遍历字典时,为什么必须调用.items()?

问题:在Python中遍历字典时,为什么必须调用.items()?

为什么需要调用items()以遍历字典中的键,值对?即。

dic = {'one': '1', 'two': '2'}
for k, v in dic.items():
    print(k, v)

为什么不是在字典上进行迭代的默认行为

for k, v in dic:
    print(k, v)

Why do you have to call items() to iterate over key, value pairs in a dictionary? ie.

dic = {'one': '1', 'two': '2'}
for k, v in dic.items():
    print(k, v)

Why isn’t that the default behavior of iterating over a dictionary

for k, v in dic:
    print(k, v)

回答 0

对于每个python容器C,期望是

for item in C:
    assert item in C

会顺利通过- 如果一种感觉(循环子句)与另一种感觉(存在检查)完全不同,会不会感到惊讶in?我一定会的!它自然适用于列表,集合,元组,…

因此,当C是一个字典时,如果infor循环生成键/值元组,那么,根据最小惊讶的原理,in还必须将其元组作为其包含检查中的左操作数。

那会有用吗?好看不中用的确,基本上做if (key, value) in C的代名词if C.get(key) == value-这是一张支票,我相信我可能已经执行,或要执行,100倍以上的很少比if k in C实际手段,检查钥匙的存在,完全无视值。

另一方面,只在键上循环很常见,例如:

for k in thedict:
    thedict[k] += 1

拥有价值也无济于事:

for k, v in thedict.items():
    thedict[k] = v + 1

实际上有点不太清晰和简洁。(请注意,这items是用于获取键/值对的“正确”方法的原始拼写:不幸的是,这是在此类访问器返回整个列表的时代,因此,为了支持“公正迭代”,必须引入替代拼写,并且iteritems 在-Python 3中,与以前的Python版本的向后兼容性约束被大大削弱,后来items又变成了)。

For every python container C, the expectation is that

for item in C:
    assert item in C

will pass just fine — wouldn’t you find it astonishing if one sense of in (the loop clause) had a completely different meaning from the other (the presence check)? I sure would! It naturally works that way for lists, sets, tuples, …

So, when C is a dictionary, if in were to yield key/value tuples in a for loop, then, by the principle of least astonishment, in would also have to take such a tuple as its left-hand operand in the containment check.

How useful would that be? Pretty useless indeed, basically making if (key, value) in C a synonym for if C.get(key) == value — which is a check I believe I may have performed, or wanted to perform, 100 times more rarely than what if k in C actually means, checking the presence of the key only and completely ignoring the value.

On the other hand, wanting to loop just on keys is quite common, e.g.:

for k in thedict:
    thedict[k] += 1

having the value as well would not help particularly:

for k, v in thedict.items():
    thedict[k] = v + 1

actually somewhat less clear and less concise. (Note that items was the original spelling of the “proper” methods to use to get key/value pairs: unfortunately that was back in the days when such accessors returned whole lists, so to support “just iterating” an alternative spelling had to be introduced, and iteritems it was — in Python 3, where backwards compatibility constraints with previous Python versions were much weakened, it became items again).


回答 1

我的猜测:使用完整的元组进行循环会更直观,但使用进行成员资格测试可能会更不那么直观in

if key in counts:
    counts[key] += 1
else:
    counts[key] = 1

如果您必须同时指定key和value,那么该代码将无法正常工作in。我很难想象用例,您将检查键和值是否都在字典中。仅测试密钥更为自然。

# When would you ever write a condition like this?
if (key, value) in dict:

现在,in操作员和for ... in操作员不必对相同的项目进行操作。在实现方面,它们是不同的操作(__contains__vs. __iter__)。但是,这种微小的不一致会造成一些混乱,而且不一致。

My guess: Using the full tuple would be more intuitive for looping, but perhaps less so for testing for membership using in.

if key in counts:
    counts[key] += 1
else:
    counts[key] = 1

That code wouldn’t really work if you had to specify both key and value for in. I am having a hard time imagining use case where you’d check if both the key AND value are in the dictionary. It is far more natural to only test the keys.

# When would you ever write a condition like this?
if (key, value) in dict:

Now it’s not necessary that the in operator and for ... in operate over the same items. Implementation-wise they are different operations (__contains__ vs. __iter__). But that little inconsistency would be somewhat confusing and, well, inconsistent.


检查密钥是否存在,并使用Python迭代JSON数组

问题:检查密钥是否存在,并使用Python迭代JSON数组

我从Facebook帖子中获得了一堆JSON数据,如下所示:

{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}

JSON数据是半结构化的,并且所有数据都不相同。下面是我的代码:

import json 

str = '{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}'
data = json.loads(str)

post_id = data['id']
post_type = data['type']
print(post_id)
print(post_type)

created_time = data['created_time']
updated_time = data['updated_time']
print(created_time)
print(updated_time)

if data.get('application'):
    app_id = data['application'].get('id', 0)
    print(app_id)
else:
    print('null')

#if data.get('to'):
#... This is the part I am not sure how to do
# Since it is in the form "to": {"data":[{"id":...}]}

我希望代码将to_id打印为1543,否则打印’null’

我不确定该怎么做。

I have a bunch of JSON data from Facebook posts like the one below:

{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}

The JSON data is semi-structured and all is not the same. Below is my code:

import json 

str = '{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}'
data = json.loads(str)

post_id = data['id']
post_type = data['type']
print(post_id)
print(post_type)

created_time = data['created_time']
updated_time = data['updated_time']
print(created_time)
print(updated_time)

if data.get('application'):
    app_id = data['application'].get('id', 0)
    print(app_id)
else:
    print('null')

#if data.get('to'):
#... This is the part I am not sure how to do
# Since it is in the form "to": {"data":[{"id":...}]}

I want the code to print the to_id as 1543 else print ‘null’

I am not sure how to do this.


回答 0

import json

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    if 'to' not in data:
        raise ValueError("No target in given data")
    if 'data' not in data['to']:
        raise ValueError("No data for target")

    for dest in data['to']['data']:
        if 'id' not in dest:
            continue
        targetId = dest['id']
        print("to_id:", targetId)

输出:

In [9]: getTargetIds(s)
to_id: 1543
import json

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    if 'to' not in data:
        raise ValueError("No target in given data")
    if 'data' not in data['to']:
        raise ValueError("No data for target")

    for dest in data['to']['data']:
        if 'id' not in dest:
            continue
        targetId = dest['id']
        print("to_id:", targetId)

Output:

In [9]: getTargetIds(s)
to_id: 1543

回答 1

如果您只想检查密钥是否存在

h = {'a': 1}
'b' in h # returns False

如果要检查是否有密钥值

h.get('b') # returns None

如果缺少实际值,则返回默认值

h.get('b', 'Default value')

If all you want is to check if key exists or not

h = {'a': 1}
'b' in h # returns False

If you want to check if there is a value for key

h.get('b') # returns None

Return a default value if actual value is missing

h.get('b', 'Default value')

回答 2

为此类事件创建助手实用程序方法是一个好习惯,这样,每当您需要更改属性验证的逻辑时,它就会放在一个位置,并且对于跟随者而言,代码将更具可读性。

例如,在以下位置创建一个辅助方法(或JsonUtils带有静态方法的类)json_utils.py

def get_attribute(data, attribute, default_value):
    return data.get(attribute) or default_value

然后在您的项目中使用它:

from json_utils import get_attribute

def my_cool_iteration_func(data):

    data_to = get_attribute(data, 'to', None)
    if not data_to:
        return

    data_to_data = get_attribute(data_to, 'data', [])
    for item in data_to_data:
        print('The id is: %s' % get_attribute(item, 'id', 'null'))

重要的提示:

我使用的原因data.get(attribute) or default_value不是简单的data.get(attribute, default_value)

{'my_key': None}.get('my_key', 'nothing') # returns None
{'my_key': None}.get('my_key') or 'nothing' # returns 'nothing'

在我的应用程序中,获取属性值为“ null”与根本不获取属性相同。如果您的用法不同,则需要进行更改。

It is a good practice to create helper utility methods for things like that so that whenever you need to change the logic of attribute validation it would be in one place, and the code will be more readable for the followers.

For example create a helper method (or class JsonUtils with static methods) in json_utils.py:

def get_attribute(data, attribute, default_value):
    return data.get(attribute) or default_value

and then use it in your project:

from json_utils import get_attribute

def my_cool_iteration_func(data):

    data_to = get_attribute(data, 'to', None)
    if not data_to:
        return

    data_to_data = get_attribute(data_to, 'data', [])
    for item in data_to_data:
        print('The id is: %s' % get_attribute(item, 'id', 'null'))

IMPORTANT NOTE:

There is a reason I am using data.get(attribute) or default_value instead of simply data.get(attribute, default_value):

{'my_key': None}.get('my_key', 'nothing') # returns None
{'my_key': None}.get('my_key') or 'nothing' # returns 'nothing'

In my applications getting attribute with value ‘null’ is the same as not getting the attribute at all. If your usage is different, you need to change this.


回答 3

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        print("to_id:", dest.get('id', 'null'))

试试吧:

>>> getTargetIds(jsonData)
to_id: 1543
to_id: null

或者,如果您只想跳过缺少ID的值,而不是打印'null'

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        if 'id' in to_id:
            print("to_id:", dest['id'])

所以:

>>> getTargetIds(jsonData)
to_id: 1543

当然,在现实生活中,您可能不想使用print每个id,而是要存储它们并对其进行操作,但这是另一个问题。

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        print("to_id:", dest.get('id', 'null'))

Try it:

>>> getTargetIds(jsonData)
to_id: 1543
to_id: null

Or, if you just want to skip over values missing ids instead of printing 'null':

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    for dest in data['to']['data']:
        if 'id' in to_id:
            print("to_id:", dest['id'])

So:

>>> getTargetIds(jsonData)
to_id: 1543

Of course in real life, you probably don’t want to print each id, but to store them and do something with them, but that’s another issue.


回答 4

if "my_data" in my_json_data:
         print json.dumps(my_json_data["my_data"])
if "my_data" in my_json_data:
         print json.dumps(my_json_data["my_data"])

回答 5

为此,我编写了一个小函数。随时调整用途,

def is_json_key_present(json, key):
    try:
        buf = json[key]
    except KeyError:
        return False

    return True

I wrote a tiny function for this purpose. Feel free to repurpose,

def is_json_key_present(json, key):
    try:
        buf = json[key]
    except KeyError:
        return False

    return True

如何计算列表中的唯一值

问题:如何计算列表中的唯一值

因此,我试图制作一个程序来询问用户输入并将值存储在数组/列表中。
然后,当输入空白行时,它将告诉用户这些值中有多少是唯一的。
我出于现实原因而不是问题集来构建它。

enter: happy
enter: rofl
enter: happy
enter: mpg8
enter: Cpp
enter: Cpp
enter:
There are 4 unique words!

我的代码如下:

# ask for input
ipta = raw_input("Word: ")

# create list 
uniquewords = [] 
counter = 0
uniquewords.append(ipta)

a = 0   # loop thingy
# while loop to ask for input and append in list
while ipta: 
  ipta = raw_input("Word: ")
  new_words.append(input1)
  counter = counter + 1

for p in uniquewords:

..这就是到目前为止我所获得的一切。
我不确定如何计算列表中单词的唯一数量?
如果有人可以发布解决方案,以便我可以学习它,或者至少告诉我它会是多么棒,谢谢!

So I’m trying to make this program that will ask the user for input and store the values in an array / list.
Then when a blank line is entered it will tell the user how many of those values are unique.
I’m building this for real life reasons and not as a problem set.

enter: happy
enter: rofl
enter: happy
enter: mpg8
enter: Cpp
enter: Cpp
enter:
There are 4 unique words!

My code is as follows:

# ask for input
ipta = raw_input("Word: ")

# create list 
uniquewords = [] 
counter = 0
uniquewords.append(ipta)

a = 0   # loop thingy
# while loop to ask for input and append in list
while ipta: 
  ipta = raw_input("Word: ")
  new_words.append(input1)
  counter = counter + 1

for p in uniquewords:

..and that’s about all I’ve gotten so far.
I’m not sure how to count the unique number of words in a list?
If someone can post the solution so I can learn from it, or at least show me how it would be great, thanks!


回答 0

另外,使用collections.Counter重构代码:

from collections import Counter

words = ['a', 'b', 'c', 'a']

Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency

输出:

['a', 'c', 'b']
[2, 1, 1]

In addition, use collections.Counter to refactor your code:

from collections import Counter

words = ['a', 'b', 'c', 'a']

Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency

Output:

['a', 'c', 'b']
[2, 1, 1]

回答 1

您可以使用集合删除重复项,然后使用len函数计算集合中的元素:

len(set(new_words))

You can use a set to remove duplicates, and then the len function to count the elements in the set:

len(set(new_words))

回答 2

values, counts = np.unique(words, return_counts=True)

values, counts = np.unique(words, return_counts=True)


回答 3

使用一

words = ['a', 'b', 'c', 'a']
unique_words = set(words)             # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3

有了这个,您的解决方案就可以很简单:

words = []
ipta = raw_input("Word: ")

while ipta:
  words.append(ipta)
  ipta = raw_input("Word: ")

unique_word_count = len(set(words))

print "There are %d unique words!" % unique_word_count

Use a set:

words = ['a', 'b', 'c', 'a']
unique_words = set(words)             # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3

Armed with this, your solution could be as simple as:

words = []
ipta = raw_input("Word: ")

while ipta:
  words.append(ipta)
  ipta = raw_input("Word: ")

unique_word_count = len(set(words))

print "There are %d unique words!" % unique_word_count

回答 4

aa="XXYYYSBAA"
bb=dict(zip(list(aa),[list(aa).count(i) for i in list(aa)]))
print(bb)
# output:
# {'X': 2, 'Y': 3, 'S': 1, 'B': 1, 'A': 2}
aa="XXYYYSBAA"
bb=dict(zip(list(aa),[list(aa).count(i) for i in list(aa)]))
print(bb)
# output:
# {'X': 2, 'Y': 3, 'S': 1, 'B': 1, 'A': 2}

回答 5

对于ndarray,有一个称为unique的numpy方法:

np.unique(array_name)

例子:

>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])

对于系列,有一个函数调用value_counts()

Series_name.value_counts()

For ndarray there is a numpy method called unique:

np.unique(array_name)

Examples:

>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])

For a Series there is a function call value_counts():

Series_name.value_counts()

回答 6

ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list
unique_words = set(words)
ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list
unique_words = set(words)

回答 7

尽管集合是最简单的方法,但是您也可以使用some_dict.has(key)字典并仅使用唯一的键和值来填充字典。

假设您已经填充words[]了用户的输入,请创建一个字典,将列表中的唯一单词映射到数字:

word_map = {}
i = 1
for j in range(len(words)):
    if not word_map.has_key(words[j]):
        word_map[words[j]] = i
        i += 1                                                             
num_unique_words = len(new_map) # or num_unique_words = i, however you prefer

Although a set is the easiest way, you could also use a dict and use some_dict.has(key) to populate a dictionary with only unique keys and values.

Assuming you have already populated words[] with input from the user, create a dict mapping the unique words in the list to a number:

word_map = {}
i = 1
for j in range(len(words)):
    if not word_map.has_key(words[j]):
        word_map[words[j]] = i
        i += 1                                                             
num_unique_words = len(new_map) # or num_unique_words = i, however you prefer

回答 8

使用熊猫的其他方法

import pandas as pd

LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])

然后,您可以以任何所需的格式导出结果

Other method by using pandas

import pandas as pd

LIST = ["a","a","c","a","a","v","d"]
counts,values = pd.Series(LIST).value_counts().values, pd.Series(LIST).value_counts().index
df_results = pd.DataFrame(list(zip(values,counts)),columns=["value","count"])

You can then export results in any format you want


回答 9

怎么样:

import pandas as pd
#List with all words
words=[]

#Code for adding words
words.append('test')


#When Input equals blank:
pd.Series(words).nunique()

它返回列表中有多少个唯一值

How about:

import pandas as pd
#List with all words
words=[]

#Code for adding words
words.append('test')


#When Input equals blank:
pd.Series(words).nunique()

It returns how many unique values are in a list


回答 10

以下应该工作。lambda函数过滤掉重复的单词。

inputs=[]
input = raw_input("Word: ").strip()
while input:
    inputs.append(input)
    input = raw_input("Word: ").strip()
uniques=reduce(lambda x,y: ((y in x) and x) or x+[y], inputs, [])
print 'There are', len(uniques), 'unique words'

The following should work. The lambda function filter out the duplicated words.

inputs=[]
input = raw_input("Word: ").strip()
while input:
    inputs.append(input)
    input = raw_input("Word: ").strip()
uniques=reduce(lambda x,y: ((y in x) and x) or x+[y], inputs, [])
print 'There are', len(uniques), 'unique words'

回答 11

我会自己使用一套,但这是另一种方式:

uniquewords = []
while True:
    ipta = raw_input("Word: ")
    if ipta == "":
        break
    if not ipta in uniquewords:
        uniquewords.append(ipta)
print "There are", len(uniquewords), "unique words!"

I’d use a set myself, but here’s yet another way:

uniquewords = []
while True:
    ipta = raw_input("Word: ")
    if ipta == "":
        break
    if not ipta in uniquewords:
        uniquewords.append(ipta)
print "There are", len(uniquewords), "unique words!"

回答 12

ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list

while ipta: ## while loop to ask for input and append in list
  words.append(ipta)
  ipta = raw_input("Word: ")
  words.append(ipta)
#Create a set, sets do not have repeats
unique_words = set(words)

print "There are " +  str(len(unique_words)) + " unique words!"
ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list

while ipta: ## while loop to ask for input and append in list
  words.append(ipta)
  ipta = raw_input("Word: ")
  words.append(ipta)
#Create a set, sets do not have repeats
unique_words = set(words)

print "There are " +  str(len(unique_words)) + " unique words!"

在循环中如何创建不同的变量名?[重复]

问题:在循环中如何创建不同的变量名?[重复]

出于示例目的…

for x in range(0,9):
    string'x' = "Hello"

所以我最终得到了string1,string2,string3 …都等于“ Hello”

For example purposes…

for x in range(0,9):
    string'x' = "Hello"

So I end up with string1, string2, string3… all equaling “Hello”


回答 0

你当然可以; 它被称为字典

d = {}
for x in range(1, 10):
    d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
 'string2': 'Hello',
 'string3': 'Hello',
 'string4': 'Hello',
 'string5': 'Hello',
 'string6': 'Hello',
 'string7': 'Hello',
 'string8': 'Hello',
 'string9': 'Hello'}

我说的有点难以理解,但实际上将一个值与另一个值相关联的最佳方法是字典。这就是它的设计目的!

Sure you can; it’s called a dictionary:

d = {}
for x in range(1, 10):
    d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
 'string2': 'Hello',
 'string3': 'Hello',
 'string4': 'Hello',
 'string5': 'Hello',
 'string6': 'Hello',
 'string7': 'Hello',
 'string8': 'Hello',
 'string9': 'Hello'}

I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!


回答 1

这真是个坏主意,但是…

for x in range(0, 9):
    globals()['string%s' % x] = 'Hello'

然后例如:

print(string3)

会给你:

Hello

但是,这是不好的做法。如其他人建议的那样,您应该改用字典或列表。当然,除非您真的想知道如何做,但不想使用它。

It is really bad idea, but…

for x in range(0, 9):
    globals()['string%s' % x] = 'Hello'

and then for example:

print(string3)

will give you:

Hello

However this is bad practice. You should use dictionaries or lists instead, as others propose. Unless, of course, you really wanted to know how to do it, but did not want to use it.


回答 2

一种方法是使用exec()。例如:

for k in range(5):
    exec(f'cat_{k} = k*2')
>>> print(cat_0)
0
>>> print(cat_1)
2
>>> print(cat_2)
4
>>> print(cat_3)
6
>>> print(cat_4)
8

在这里,我利用了Python 3.6+中方便的f字符串格式

One way you can do this is with exec(). For example:

for k in range(5):
    exec(f'cat_{k} = k*2')
>>> print(cat_0)
0
>>> print(cat_1)
2
>>> print(cat_2)
4
>>> print(cat_3)
6
>>> print(cat_4)
8

Here I am taking advantage of the handy f string formatting in Python 3.6+


回答 3

创建变量变量名根本没有意义。为什么?

  • 它们是不必要的:您可以将所有内容存储在列表,字典等中
  • 它们很难创建:您必须使用execglobals()
  • 您不能使用它们:如何编写使用这些变量的代码?您必须exec/globals()再次使用

使用列表要容易得多:

# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
    print string
print string[6] # or pick any of them

It’s simply pointless to create variable variable names. Why?

  • They are unnecessary: You can store everything in lists, dictionarys and so on
  • They are hard to create: You have to use exec or globals()
  • You can’t use them: How do you write code that uses these variables? You have to use exec/globals() again

Using a list is much easier:

# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
    print string
print string[6] # or pick any of them

回答 4

不要使用字典

import sys
this = sys.modules[__name__] # this is now your current namespace
for x in range(0,9):
    setattr(this, 'string%s' % x, 'Hello')

print string0
print string1
print string2
print string3
print string4
print string5
print string6
print string7
print string8

不要使用字典

globals()存在风险,因为它会给您提供当前命名空间指向的内容,但是这可能会发生变化,因此修改globals()的返回值不是一个好主意

Don’t do this use a dictionary

import sys
this = sys.modules[__name__] # this is now your current namespace
for x in range(0,9):
    setattr(this, 'string%s' % x, 'Hello')

print string0
print string1
print string2
print string3
print string4
print string5
print string6
print string7
print string8

don’t do this use a dict

globals() has risk as it gives you what the namespace is currently pointing to but this can change and so modifying the return from globals() is not a good idea


回答 5

for x in range(9):
    exec("string" + str(x) + " = 'hello'")

这应该工作。

for x in range(9):
    exec("string" + str(x) + " = 'hello'")

This should work.


回答 6

我会使用一个列表:

string = []
for i in range(0, 9):
  string.append("Hello")

这样,您将拥有9个“ Hello”,并且可以像这样单独获取它们:

string[x]

哪里 x可以找到您想要的“ Hello”。

因此,print(string[1])将打印Hello

I would use a list:

string = []
for i in range(0, 9):
  string.append("Hello")

This way, you would have 9 “Hello” and you could get them individually like this:

string[x]

Where x would identify which “Hello” you want.

So, print(string[1]) would print Hello.


回答 7

我认为这里的挑战不是要调用global()

我将为要保存的(动态)变量定义一个列表,然后将其附加到for循环中。然后使用单独的for循环查看每个条目,甚至执行其他操作。

这是一个示例-我在不同的分支机构都有许多网络交换机(例如2到8之间)。现在,我需要确保有一种方法可以确定在任何给定分支上有多少个可用交换机(或活动ping测试),然后对它们执行一些操作。

这是我的代码:

import requests
import sys

def switch_name(branchNum):
    # s is an empty list to start with
    s = []
    #this FOR loop is purely for creating and storing the dynamic variable names in s
    for x in range(1,8,+1):
        s.append("BR" + str(branchNum) + "SW0" + str(x))

    #this FOR loop is used to read each of the switch in list s and perform operations on
    for i in s:
        print(i,"\n")
        # other operations can be executed here too for each switch (i) - like SSH in using paramiko and changing switch interface VLAN etc.


def main():  

    # for example's sake - hard coding the site code
    branchNum= "123"
    switch_name(branchNum)


if __name__ == '__main__':
    main()

输出为:

BR123SW01

BR123SW02

BR123SW03

BR123SW04

BR123SW05

BR123SW06

BR123SW07

I think the challenge here is not to call upon global()

I would personally define a list for your (dynamic) variables to be held and then append to it within a for loop. Then use a separate for loop to view each entry or even execute other operations.

Here is an example – I have a number of network switches (say between 2 and 8) at various BRanches. Now I need to ensure I have a way to determining how many switches are available (or alive – ping test) at any given branch and then perform some operations on them.

Here is my code:

import requests
import sys

def switch_name(branchNum):
    # s is an empty list to start with
    s = []
    #this FOR loop is purely for creating and storing the dynamic variable names in s
    for x in range(1,8,+1):
        s.append("BR" + str(branchNum) + "SW0" + str(x))

    #this FOR loop is used to read each of the switch in list s and perform operations on
    for i in s:
        print(i,"\n")
        # other operations can be executed here too for each switch (i) - like SSH in using paramiko and changing switch interface VLAN etc.


def main():  

    # for example's sake - hard coding the site code
    branchNum= "123"
    switch_name(branchNum)


if __name__ == '__main__':
    main()

Output is:

BR123SW01

BR123SW02

BR123SW03

BR123SW04

BR123SW05

BR123SW06

BR123SW07


回答 8

使用字典应该是保留变量和关联值的正确方法,您可以使用以下方法:

dict_ = {}
for i in range(9):
     dict_['string%s' % i]  = 'Hello'

但是,如果要将变量添加到局部变量中,可以使用:

for i in range(9):
     exec('string%s = Hello' % i)

例如,如果要为它们分配值0到8,则可以使用:

for i in range(9):
     exec('string%s = %s' % (i,i))

Using dictionaries should be right way to keep the variables and associated values, and you may use this:

dict_ = {}
for i in range(9):
     dict_['string%s' % i]  = 'Hello'

But if you want to add the variables to the local variables you can use:

for i in range(9):
     exec('string%s = Hello' % i)

And for example if you want to assign values 0 to 8 to them, you may use:

for i in range(9):
     exec('string%s = %s' % (i,i))

回答 9

字典可以包含值,并且可以使用update()方法添加值。您希望系统创建变量,因此您应该知道保留位置。

variables = {}
break_condition= True # Dont forget to add break condition to while loop if you dont want your system to go crazy.
name = variable
i = 0 
name = name + str(i) #this will be your variable name.
while True:
    value = 10 #value to assign
    variables.update(
                  {name:value})
    if break_condition == True:
        break

Dictionary can contain values and values can be added by using update() method. You want your system to create variables, so you should know where to keep.

variables = {}
break_condition= True # Dont forget to add break condition to while loop if you dont want your system to go crazy.
name = “variable”
i = 0 
name = name + str(i) #this will be your variable name.
while True:
    value = 10 #value to assign
    variables.update(
                  {name:value})
    if break_condition == True:
        break

numpy如何迭代数组的列?

问题:numpy如何迭代数组的列?

假设我有和mxn数组。我想将此数组的每一列传递给函数,以对整个列执行一些操作。如何遍历数组的列?

例如,我有一个4 x 3的数组

1  99 2
2  14 5
3  12 7
4  43 1

for column in array:
  some_function(column)

其中列在第一次迭代中将为“ 1,2,3,4”,在第二次迭代中为“ 99,14,12,43”,在第三次迭代中为“ 2,5,7,1”。

Suppose I have and m x n array. I want to pass each column of this array to a function to perform some operation on the entire column. How do I iterate over the columns of the array?

For example, I have a 4 x 3 array like

1  99 2
2  14 5
3  12 7
4  43 1

for column in array:
  some_function(column)

where column would be “1,2,3,4” in the first iteration, “99,14,12,43” in the second, and “2,5,7,1” in the third.


回答 0

只需遍历数组的转置即可:

for column in array.T:
   some_function(column)

Just iterate over the transposed of your array:

for column in array.T:
   some_function(column)

回答 1

这应该给你一个开始

>>> for col in range(arr.shape[1]):
    some_function(arr[:,col])


[1 2 3 4]
[99 14 12 43]
[2 5 7 1]

This should give you a start

>>> for col in range(arr.shape[1]):
    some_function(arr[:,col])


[1 2 3 4]
[99 14 12 43]
[2 5 7 1]

回答 2

对于三维数组,您可以尝试:

for c in array.transpose(1, 0, 2):
    do_stuff(c)

请参阅有关array.transpose工作原理的文档。基本上,您要指定要移动的尺寸。在这种情况下,我们将第二维(例如列)移动到第一维。

For a three dimensional array you could try:

for c in array.transpose(1, 0, 2):
    do_stuff(c)

See the docs on how array.transpose works. Basically you are specifying which dimension to shift. In this case we are shifting the second dimension (e.g. columns) to the first dimension.


回答 3

for c in np.hsplit(array, array.shape[1]):
    some_fun(c)
for c in np.hsplit(array, array.shape[1]):
    some_fun(c)

回答 4

您还可以使用解压缩来遍历各列

for col in zip(*array):
   some_function(col)

You can also use unzip to iterate through the columns

for col in zip(*array):
   some_function(col)

回答 5

例如,您要查找矩阵中每一列的平均值。让我们创建以下矩阵

mat2 = np.array([1,5,6,7,3,0,3,5,9,10,8,0], dtype=np.float64).reshape(3, 4)

均值的函数是

def my_mean(x):
    return sum(x)/len(x)

执行所需的操作并将结果存储在结肠向量“结果”中

results = np.zeros(4)
for i in range(0, 4):
    mat2[:, i] = my_mean(mat2[:, i])

results = mat2[1,:]      

结果是:array([4.33333333,5.,5.66666667,4.])

For example you want to find a mean of each column in matrix. Let’s create the following matrix

mat2 = np.array([1,5,6,7,3,0,3,5,9,10,8,0], dtype=np.float64).reshape(3, 4)

The function for mean is

def my_mean(x):
    return sum(x)/len(x)

To do what is needed and store result in colon vector ‘results’

results = np.zeros(4)
for i in range(0, 4):
    mat2[:, i] = my_mean(mat2[:, i])

results = mat2[1,:]      

The results are: array([4.33333333, 5. , 5.66666667, 4. ])


回答 6

或者,您可以使用enumerate。它也为您提供列号和列值。

for num, column in enumerate(array.T):
    some_function(column) # column: Gives you the column value as asked in the question
    some_function(num) # num: Gives you the column number 

Alternatively, you can use enumerate. It gives you the column number and the column values as well.

for num, column in enumerate(array.T):
    some_function(column) # column: Gives you the column value as asked in the question
    some_function(num) # num: Gives you the column number 



遍历JSON对象

问题:遍历JSON对象

我正在尝试遍历JSON对象以导入数据,即标题和链接。我似乎无法掌握过去的内容:

JSON:

[
    {
        "title": "Baby (Feat. Ludacris) - Justin Bieber",
        "description": "Baby (Feat. Ludacris) by Justin Bieber on Grooveshark",
        "link": "http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq",
        "pubDate": "Wed, 28 Apr 2010 02:37:53 -0400",
        "pubTime": 1272436673,
        "TinyLink": "http://tinysong.com/d3wI",
        "SongID": "24447862",
        "SongName": "Baby (Feat. Ludacris)",
        "ArtistID": "1118876",
        "ArtistName": "Justin Bieber",
        "AlbumID": "4104002",
        "AlbumName": "My World (Part II);\nhttp://tinysong.com/gQsw",
        "LongLink": "11578982",
        "GroovesharkLink": "11578982",
        "Link": "http://tinysong.com/d3wI"
    },
    {
        "title": "Feel Good Inc - Gorillaz",
        "description": "Feel Good Inc by Gorillaz on Grooveshark",
        "link": "http://listen.grooveshark.com/s/Feel+Good+Inc/1UksmI",
        "pubDate": "Wed, 28 Apr 2010 02:25:30 -0400",
        "pubTime": 1272435930
    }
]

我尝试使用字典:

def getLastSong(user,limit):
    base_url = 'http://gsuser.com/lastSong/'
    user_url = base_url + str(user) + '/' + str(limit) + "/"
    raw = urllib.urlopen(user_url)
    json_raw= raw.readlines()
    json_object = json.loads(json_raw[0])

    #filtering and making it look good.
    gsongs = []
    print json_object
    for song in json_object[0]:   
        print song

此代码仅在之前打印信息:。(忽略贾斯汀·比伯的曲目:)

I am trying to iterate through a JSON object to import data, i.e. title and link. I can’t seem to get to the content that is past the :.

JSON:

[
    {
        "title": "Baby (Feat. Ludacris) - Justin Bieber",
        "description": "Baby (Feat. Ludacris) by Justin Bieber on Grooveshark",
        "link": "http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq",
        "pubDate": "Wed, 28 Apr 2010 02:37:53 -0400",
        "pubTime": 1272436673,
        "TinyLink": "http://tinysong.com/d3wI",
        "SongID": "24447862",
        "SongName": "Baby (Feat. Ludacris)",
        "ArtistID": "1118876",
        "ArtistName": "Justin Bieber",
        "AlbumID": "4104002",
        "AlbumName": "My World (Part II);\nhttp://tinysong.com/gQsw",
        "LongLink": "11578982",
        "GroovesharkLink": "11578982",
        "Link": "http://tinysong.com/d3wI"
    },
    {
        "title": "Feel Good Inc - Gorillaz",
        "description": "Feel Good Inc by Gorillaz on Grooveshark",
        "link": "http://listen.grooveshark.com/s/Feel+Good+Inc/1UksmI",
        "pubDate": "Wed, 28 Apr 2010 02:25:30 -0400",
        "pubTime": 1272435930
    }
]

I tried using a dictionary:

def getLastSong(user,limit):
    base_url = 'http://gsuser.com/lastSong/'
    user_url = base_url + str(user) + '/' + str(limit) + "/"
    raw = urllib.urlopen(user_url)
    json_raw= raw.readlines()
    json_object = json.loads(json_raw[0])

    #filtering and making it look good.
    gsongs = []
    print json_object
    for song in json_object[0]:   
        print song

This code only prints the information before :. (ignore the Justin Bieber track :))


回答 0

您加载JSON数据有些脆弱。代替:

json_raw= raw.readlines()
json_object = json.loads(json_raw[0])

您实际上应该这样做:

json_object = json.load(raw)

您不应该将“ JSON对象”视为什么。您所拥有的是清单。该列表包含两个字典。字典包含各种键/值对,所有字符串。当您这样做时json_object[0],您将要求列表中的第一个字典。当您使用进行迭代时for song in json_object[0]:,您将遍历字典的键。因为那是您遍历dict时得到的。如果要访问与该字典中的键关联的值,则可以使用json_object[0][song]

这些都不是特定于JSON的。这只是基本的Python类型,其基本操作如本教程所述。

Your loading of the JSON data is a little fragile. Instead of:

json_raw= raw.readlines()
json_object = json.loads(json_raw[0])

you should really just do:

json_object = json.load(raw)

You shouldn’t think of what you get as a “JSON object”. What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do json_object[0], you’re asking for the first dict in the list. When you iterate over that, with for song in json_object[0]:, you iterate over the keys of the dict. Because that’s what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, json_object[0][song].

None of this is specific to JSON. It’s just basic Python types, with their basic operations as covered in any tutorial.


回答 1

我相信您可能是说:

from __future__ import print_function

for song in json_object:
    # now song is a dictionary
    for attribute, value in song.items():
        print(attribute, value) # example usage

注意:您可以在Python 2中使用if song.iteritems代替song.items

I believe you probably meant:

from __future__ import print_function

for song in json_object:
    # now song is a dictionary
    for attribute, value in song.items():
        print(attribute, value) # example usage

NB: You could use song.iteritems instead of song.items if in Python 2.


回答 2

这个问题已经存在很长时间了,但是我想贡献我通常如何遍历JSON对象的方式。在下面的示例中,我显示了一个包含JSON的硬编码字符串,但是JSON字符串也可以很容易地来自Web服务或文件。

import json

def main():

    # create a simple JSON array
    jsonString = '{"key1":"value1","key2":"value2","key3":"value3"}'

    # change the JSON string into a JSON object
    jsonObject = json.loads(jsonString)

    # print the keys and values
    for key in jsonObject:
        value = jsonObject[key]
        print("The key and value are ({}) = ({})".format(key, value))

    pass

if __name__ == '__main__':
    main()

This question has been out here a long time, but I wanted to contribute how I usually iterate through a JSON object. In the example below, I’ve shown a hard-coded string that contains the JSON, but the JSON string could just as easily have come from a web service or a file.

import json

def main():

    # create a simple JSON array
    jsonString = '{"key1":"value1","key2":"value2","key3":"value3"}'

    # change the JSON string into a JSON object
    jsonObject = json.loads(jsonString)

    # print the keys and values
    for key in jsonObject:
        value = jsonObject[key]
        print("The key and value are ({}) = ({})".format(key, value))

    pass

if __name__ == '__main__':
    main()

回答 3

反序列化JSON之后,您将拥有一个python对象。使用常规对象方法。

在这种情况下,您有一个由字典组成的列表:

json_object[0].items()

json_object[0]["title"]

等等

After deserializing the JSON, you have a python object. Use the regular object methods.

In this case you have a list made of dictionaries:

json_object[0].items()

json_object[0]["title"]

etc.


回答 4

我会这样解决这个问题

import json
import urllib2

def last_song(user, limit):
    # Assembling strings with "foo" + str(bar) + "baz" + ... generally isn't 
    # as nice as using real string formatting. It can seem simpler at first, 
    # but leaves you less happy in the long run.
    url = 'http://gsuser.com/lastSong/%s/%d/' % (user, limit)

    # urllib.urlopen is deprecated in favour of urllib2.urlopen
    site = urllib2.urlopen(url)

    # The json module has a function load for loading from file-like objects, 
    # like the one you get from `urllib2.urlopen`. You don't need to turn 
    # your data into a string and use loads and you definitely don't need to 
    # use readlines or readline (there is seldom if ever reason to use a 
    # file-like object's readline(s) methods.)
    songs = json.load(site)

    # I don't know why "lastSong" stuff returns something like this, but 
    # your json thing was a JSON array of two JSON objects. This will 
    # deserialise as a list of two dicts, with each item representing 
    # each of those two songs.
    #
    # Since each of the songs is represented by a dict, it will iterate 
    # over its keys (like any other Python dict). 
    baby, feel_good = songs

    # Rather than printing in a function, it's usually better to 
    # return the string then let the caller do whatever with it. 
    # You said you wanted to make the output pretty but you didn't 
    # mention *how*, so here's an example of a prettyish representation
    # from the song information given.
    return "%(SongName)s by %(ArtistName)s - listen at %(link)s" % baby

I would solve this problem more like this

import json
import urllib2

def last_song(user, limit):
    # Assembling strings with "foo" + str(bar) + "baz" + ... generally isn't 
    # as nice as using real string formatting. It can seem simpler at first, 
    # but leaves you less happy in the long run.
    url = 'http://gsuser.com/lastSong/%s/%d/' % (user, limit)

    # urllib.urlopen is deprecated in favour of urllib2.urlopen
    site = urllib2.urlopen(url)

    # The json module has a function load for loading from file-like objects, 
    # like the one you get from `urllib2.urlopen`. You don't need to turn 
    # your data into a string and use loads and you definitely don't need to 
    # use readlines or readline (there is seldom if ever reason to use a 
    # file-like object's readline(s) methods.)
    songs = json.load(site)

    # I don't know why "lastSong" stuff returns something like this, but 
    # your json thing was a JSON array of two JSON objects. This will 
    # deserialise as a list of two dicts, with each item representing 
    # each of those two songs.
    #
    # Since each of the songs is represented by a dict, it will iterate 
    # over its keys (like any other Python dict). 
    baby, feel_good = songs

    # Rather than printing in a function, it's usually better to 
    # return the string then let the caller do whatever with it. 
    # You said you wanted to make the output pretty but you didn't 
    # mention *how*, so here's an example of a prettyish representation
    # from the song information given.
    return "%(SongName)s by %(ArtistName)s - listen at %(link)s" % baby

回答 5

通过JSON进行迭代,您可以使用以下代码:

json_object = json.loads(json_file)
for element in json_object: 
    for value in json_object['Name_OF_YOUR_KEY/ELEMENT']:
        print(json_object['Name_OF_YOUR_KEY/ELEMENT']['INDEX_OF_VALUE']['VALUE'])

for iterating through JSON you can use this:

json_object = json.loads(json_file)
for element in json_object: 
    for value in json_object['Name_OF_YOUR_KEY/ELEMENT']:
        print(json_object['Name_OF_YOUR_KEY/ELEMENT']['INDEX_OF_VALUE']['VALUE'])

回答 6

对于Python 3,您必须解码从Web服务器获取的数据。例如,我将数据解码为utf8,然后对其进行处理:

 # example of json data object group with two values of key id
jsonstufftest = '{'group':{'id':'2','id':'3'}}
 # always set your headers
headers = {'User-Agent': 'Moz & Woz'}
 # the url you are trying to load and get json from
url = 'http://www.cooljson.com/cooljson.json'
 # in python 3 you can build the request using request.Request
req = urllib.request.Request(url,None,headers)
 # try to connect or fail gracefully
try:
    response = urllib.request.urlopen(req) # new python 3 code -jc
except:
    exit('could not load page, check connection')
 # read the response and DECODE
html=response.read().decode('utf8') # new python3 code
 # now convert the decoded string into real JSON
loadedjson = json.loads(html)
 # print to make sure it worked
print (loadedjson) # works like a charm
 # iterate through each key value
for testdata in loadedjson['group']:
    print (accesscount['id']) # should print 2 then 3 if using test json

如果不解码,Python 3中将得到字节与字符串错误。

For Python 3, you have to decode the data you get back from the web server. For instance I decode the data as utf8 then deal with it:

 # example of json data object group with two values of key id
jsonstufftest = '{'group':{'id':'2','id':'3'}}
 # always set your headers
headers = {'User-Agent': 'Moz & Woz'}
 # the url you are trying to load and get json from
url = 'http://www.cooljson.com/cooljson.json'
 # in python 3 you can build the request using request.Request
req = urllib.request.Request(url,None,headers)
 # try to connect or fail gracefully
try:
    response = urllib.request.urlopen(req) # new python 3 code -jc
except:
    exit('could not load page, check connection')
 # read the response and DECODE
html=response.read().decode('utf8') # new python3 code
 # now convert the decoded string into real JSON
loadedjson = json.loads(html)
 # print to make sure it worked
print (loadedjson) # works like a charm
 # iterate through each key value
for testdata in loadedjson['group']:
    print (accesscount['id']) # should print 2 then 3 if using test json

If you don’t decode you will get bytes vs string errors in Python 3.