Python:循环遍历列表项x次?
我正在使用Python2.7,我想在列表中循环x次Python:循环遍历列表项x次?,python,python-2.7,Python,Python 2.7,我正在使用Python2.7,我想在列表中循环x次 a=['string1','string2','string3','string4','string5'] for item in a: print item 上面的代码将打印列表中的所有五项,如果我只想打印前三项呢?我在互联网上搜索了一下,但没有找到答案,似乎xrange()可以解决这个问题,但我不知道如何解决 谢谢你的帮助 就是你要找的。在这种情况下,您需要将序列切片到前三个元素,以便打印它们 a=['string1','string
a=['string1','string2','string3','string4','string5']
for item in a:
print item
上面的代码将打印列表中的所有五项,如果我只想打印前三项呢?我在互联网上搜索了一下,但没有找到答案,似乎xrange()可以解决这个问题,但我不知道如何解决
谢谢你的帮助 就是你要找的。在这种情况下,您需要将序列切片到前三个元素,以便打印它们
a=['string1','string2','string3','string4','string5']
for i in xrange(3):
print a[i]
a=['string1','string2','string3','string4','string5']
for item in a[:3]:
print item
甚至,您也不需要在序列上循环,只需使用换行符将其打印出来即可
print '\n'.join(a[:3])
我认为这会被认为是蟒蛇式的: 编辑:由于几秒钟的时间,这个答案变得多余,我将尝试提供一些背景信息: 数组切片允许快速选择字符串列表等序列。一维序列的子序列可以由左右端点的索引指定:
>>> [1,2,3,4,5][:3] # every item with an index position < 3
[1, 2, 3]
>>> [1,2,3,4,5][3:] # every item with an index position >= 3
[4, 5]
>>> [1,2,3,4,5][2:3] # every item with an index position within the interval [2,3)
[3]
通过将列表转换为数组,甚至可以执行多维切片:
>>> numpy.array([[1,2,3,4,5], [1,2,3,4,5]])[:, ::2]
array([[1, 3, 5],
[1, 3, 5]])
谢谢,它可以工作,序列切片也可以用来切片元组列表,例如a=[('string1','string2'),('string3','string4'),('string5','string6')]@michelle26:
序列切片也可以用来切片元组列表…
,这是一个问题还是一个陈述?如果你想加入这个列表,你需要把它展平。汉克斯·阿比吉特,这不是一个问题,我很高兴序列切片可以做很多有用的事情tasks@Wim当前位置我不确定,我明白你的意思。列表已被展平,您只需将其通过str.join
>>> [1,2,3,4,5][::2] # select every second item from list
[1, 3, 5]
>>> [1,2,3,4,5][::-1] # select every single item in reverse order
[5,4,3,2,1]
>>> [1,2,3,4,5][1:4:2] # every second item from subsequence [1,4) = [2,3,4]
[2, 4]
>>> numpy.array([[1,2,3,4,5], [1,2,3,4,5]])[:, ::2]
array([[1, 3, 5],
[1, 3, 5]])