对列表和字符串的迭代 [英] Iteration over Lists and Strings

查看:58
本文介绍了对列表和字符串的迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到以下内容:

a =''abba''
for n in a:
print n,a.index (n)
a 0

b 1

b 1

a 0


(预期结果:

a 0

b 1

b 2

a 3)


与列表相同:List = [1,0,1]
列表中的n:
print n,List.index(n)
1 0

0 1

1 0

(预期结果:

1 0

0 1

1 2)


发生了什么事?有人可以向我澄清这个吗?我怎样才能确保迭代产生绝对索引号**而不做**

类似于:a =''abba''
k = len(a)
对于范围内的m(0,k):
打印a [m],m



a 0
b 1

b 2

a 3


谢谢 -

解决方案

2004年8月28日星期六03:22:48 GMT,DeepBleu< de ****** @ deepbleu.org>写道:

发生了什么事?有人可以向我澄清这个吗?我怎样才能确保迭代产生绝对索引号**而不做**如下所示:

a ='' abba''
k = len(a)
m在范围内(0,k):
打印a [m],m


index()方法在

列表/序列中查找给定对象的第一个索引。你想要的是使用enumerate()内置:

a =''abba''
for i,c in enumerate(a):



....打印c,i

....

a 0

b 1

b 2

a 3


和枚举比索引更快。


DeepBleu< De ****** @ DeepBleu.org>写道:

我注意到以下内容:

a =''abba''

打印n,a.index(n)a 0
b 1
b 1
a 0


a.index( n)返回FIR的索引x,使得a [x] == n。

(预期结果:
a 0
b 1
b 2
a 3)


错误的预期。第一个''b''和第二个''b''相等,对于

的例子,所以a.index永远不可能为它们返回不同的结果。


发生了什么事?有人可以向我澄清这个吗?我怎样才能确保迭代产生绝对索引号**而不做**如下:a ='''abba''
k = len(a)
对于范围内的m(0,k):
打印a [m],m


a 0
b 1
b 2 br /> a 3




这就是枚举内置的内容:


表示m,n in枚举(a):

打印n,m

Alex


I noticed the following:

a = ''abba''
for n in a:
print n, a.index(n) a 0
b 1
b 1
a 0

(expected result:
a 0
b 1
b 2
a 3)

The same with lists:List = [1, 0 , 1]
for n in List:
print n, List.index(n) 1 0
0 1
1 0

(expected result:
1 0
0 1
1 2)

What is going on? Can someone clarify this to me? And how can I ensure
that the iteration produces the absolute index number **without** doing
something like:a = ''abba''
k = len(a)
for m in range(0, k):
print a[m], m


a 0
b 1
b 2
a 3

Thanks -

解决方案

On Sat, 28 Aug 2004 03:22:48 GMT, DeepBleu <de******@deepbleu.org> wrote:

What is going on? Can someone clarify this to me? And how can I ensure
that the iteration produces the absolute index number **without** doing
something like:

a = ''abba''
k = len(a)
for m in range(0, k):
print a[m], m
The index() method looks up the first index of the given object in the
list/sequence. What you want is to use the enumerate() builtin:
a = ''abba''
for i, c in enumerate(a):


.... print c, i
....
a 0
b 1
b 2
a 3


and enumerate is more fast than index.


DeepBleu <De******@DeepBleu.org> wrote:

I noticed the following:

a = ''abba''
for n in a:
print n, a.index(n) a 0
b 1
b 1
a 0
a.index(n) returns the FIRST index x of a such thatn a[x]==n.
(expected result:
a 0
b 1
b 2
a 3)
Misfounded expectation. The first ''b'' and the second ''b'' are equal, for
example, so a.index can never possibly return different results for
them.

What is going on? Can someone clarify this to me? And how can I ensure
that the iteration produces the absolute index number **without** doing
something like:a = ''abba''
k = len(a)
for m in range(0, k):
print a[m], m


a 0
b 1
b 2
a 3



That''s what the enumerate built-in is for:

for m, n in enumerate(a):
print n, m
Alex


这篇关于对列表和字符串的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆