相关疑难解决方法(0)

迭代Python 3中的数组

我没有编写一段时间并尝试重新使用Python.我正在尝试编写一个简单的程序,通过将每个数组元素值添加到一个总和来对数组求和.这就是我所拥有的:

def sumAnArray(ar):
    theSum = 0
    for i in ar:
        theSum = theSum + ar[i]
    print(theSum)
    return theSum
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

line 13, theSum = theSum + ar[i]
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

我发现我正在尝试做的事情显然就像这样简单:

sum(ar)
Run Code Online (Sandbox Code Playgroud)

但显然我并没有正确地遍历数组,我认为这是我需要为其他目的正确学习的东西.谢谢!

python arrays sum python-3.x

12
推荐指数
2
解决办法
4万
查看次数

是否有更多的pythonic,可能是一个衬里,迭代列表中的字符串?

字符串是可迭代的.列表是可迭代的.使用字符串列表,列表和字符串都可以通过嵌套循环进行迭代.

例如:

input = [ 'abcdefg', 'hijklmn', 'opqrstu']
for item in input:
     for letter in item:
        print letter
Run Code Online (Sandbox Code Playgroud)

日期:

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
Run Code Online (Sandbox Code Playgroud)

似乎我们可以在迭代中迭代字符串,即迭代'abcdefg'的每个字母.是否有一种更加pythonic的方式如上所述迭代,可能在一个语句中?

我已经通过学习Python第4章,Python Cookbook的第1章重新阅读,并在python中查看:迭代列表中的每个字符串,并在此处显示并迭代字符串中的列表.

python string iteration list

3
推荐指数
1
解决办法
201
查看次数

如何迭代列表中的每个单词

我是Python新手。我需要从列表中逐个迭代单词。但我只能垂直迭代每个单词中的每个字母。

l = ['abcd efgh ijkl']

for i in l:
    for j in i:
        print(j)
Run Code Online (Sandbox Code Playgroud)

输出:

a
b
c
d
 
e
f
g
h
 
i
j
k
l
Run Code Online (Sandbox Code Playgroud)

预期输出:

abcd
efgh
ijkl
Run Code Online (Sandbox Code Playgroud)

python

0
推荐指数
1
解决办法
62
查看次数

标签 统计

python ×3

arrays ×1

iteration ×1

list ×1

python-3.x ×1

string ×1

sum ×1