1我循环遍历一系列数字,查找数字范围(例如<100)。
例如: list = 1,2,3,125,7,8,9,200。我想要一个档案: 1-3,7-9。我面临的问题是,外部循环会重复内部循环中的项,所以我得到的输出是: 1-3,2-3,3,7- 9,8-9,9。
我目前的策略是:
counter = 1
for i in range(len(list)): # outer loop
if counter > 1: # prevents the outer loop from iterating the numbers iterated in inner loop
counter -= 1
continue
elif counter <=1:
while list[i] < 100:
i +=1
counter +=1
if list[i] > 100:
print list[i-counter], '-', list[i]
break我想知道是否有一种更具pythonic风格的方法让外部循环跳过内部循环中迭代过的项,而不是使用额外的计数器(就像我上面做的那样)。谢谢。
编辑:关注连续数字的回复很少。我的错误是,数字不必是连续的。我只需要该范围内的第一个和最后一个数字,例如list = 1,4,8,12,57,200,4,34,300。输出:1- 57,4- 34。列表和条件取决于用户。条件将始终是带有比较运算符“<”的数字。谢谢。
发布于 2013-02-01 00:58:33
你不需要两个循环。一个就足够了:
def ranges(seq):
it = iter(seq)
start = end = next(it)
for val in it:
if val == end + 1:
end = val
else:
if end - start > 1:
yield start, end
start = end = next(it)
for start, end in ranges([1, 2, 3, 125, 7, 8, 9, 200]):
print('%d-%d' % (start, end))逻辑与您的略有不同:它查找由连续数字组成的子序列(在您的示例中为1 2 3和7 8 9 )。如果需要,可以很容易地更改逻辑以在任何数字>= 100处中断序列。
发布于 2013-02-01 01:18:48
另一种方法,基于while循环:
def print_ranges(given_list, limit):
while given_list:
start = end = given_list.pop(0)
if start < limit:
while given_list and (given_list[0] < limit):
end = given_list.pop(0)
if (end != start):
print "%d-%d"%(start,end) # or save it in another list一些测试:
>>> print_ranges([1,4,8, 200, 4,34, 72, 300], 100)
1-8
34-72
>>> print_ranges([1, 4, 8, 12, 57, 200, 4, 34, 300], 100)
1-57
4-34
>>> print_ranges([1, 4, 8, 12, 57, 200, 4, 34, 300], 250)
1-34发布于 2013-02-01 01:24:32
使用zip()
zip(lis,lis[1:])返回如下内容:
[(0, 1),
(1, 2),
(2, 3),
(3, 5),
(5, 6),...]现在,您可以遍历此列表以检查差值是否为1。
代码:
In [103]: def ranges(lis):
ans=[]
z=zip(lis,lis[1:])
for x,y in z:
if y-x==1:
ans.extend([x,y])
else:
if ans:
yield "{0}-{1}".format(min(ans),max(ans))
ans=[]
if ans:
yield "{0}-{1}".format(min(ans),max(ans))
.....:
In [104]: lis=[0,1,2,3,5,6,7,8,10,11,2,3,4]
In [105]: list(ranges(lis))
Out[105]: ['0-3', '5-8', '10-11', '2-4']https://stackoverflow.com/questions/14631006
复制相似问题