if-else语句使用list,Generalized语句

时间:2013-11-18 07:26:32

标签: python list if-statement int

我有五个清单:

Values2 = ['0','1']
Values3 = ['0','1','2']
Values4 = ['0','1','2','3']
Values5 = ['0','1','2','3','4']
Values6 = ['0','1','2','3','4','5']

每个列表中的这些值在0到5之间变化,因为示例values2变为['2','5']

现在我对第一个列表values2的if-else语句如下:

if(int(Values[0]) <= int(Values[1])):
    myAction1(Values[1]) 
else: 
    NoOfMoves = int(Values[0])-int(Values[1])
    myAction2(NoOfMoves) 

任何人都可以指导我如何概括这个声明,以便它适用于每个列表。

1 个答案:

答案 0 :(得分:0)

您可以创建列表列表并迭代它。 例如:

>>> a = range(1)
>>> c = range(10)
>>> b = range(4)
>>> b = range(7)
>>> a
[0, 1, 2, 3]
>>> b
[0, 1, 2, 3, 4, 5, 6]
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> [a,b,c]
[[0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
>>>
>>> for lst in [a,b,c]:
...     print lst
...
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for lst in [a,b,c]:
...     for element in lst:
...             print element
...
0
1
...