我有一个清单:
a = ["748","994","530","47","178","908","374","188","88","78","56","93","30",
"197","39","0","160","205","69","98","58","55","50","31","19","13","11",
"20","20","15","650","175","259","87","193","59","48","47","19","18",
"30","14","21"]
如何在一行上打印前17个元素,然后在新行上接下来的17个元素一直打印到最后?如果有可能创建一个函数,而不是:
print a[:18]
print[18:36]
....
print [n-17:n+1]
我想将它们转换为数字。
谢谢
答案 0 :(得分:1)
range
接受(可选)start
,stop
,(可选)step
个参数:
使用它你可以得到起始索引:0,17,34 ...... ....
使用切片表示法,您可以获得所需的子列表。
>>> a = ["748","994","530","47","178","908","374","188","88","78","56","93", ...]
>>> for i in range(0, len(a), 17):
... print a[i:i+17]
...
['748', '994', '530', '47', '178', '908', '374', '188', '88', '78', '56', '93', '30', '197', '39', '0', '160']
['205', '69', '98', '58', '55', '50', '31', '19', '13', '11', '20', '20', '15', '650', '175', '259', '87']
['193', '59', '48', '47', '19', '18', '30', '14', '21']
>>> for i in range(0, len(a), 17):
... print ' '.join(a[i:i+17])
...
748 994 530 47 178 908 374 188 88 78 56 93 30 197 39 0 160
205 69 98 58 55 50 31 19 13 11 20 20 15 650 175 259 87
193 59 48 47 19 18 30 14 21
答案 1 :(得分:0)
这可能会有所帮助
print "\n".join(str(a[i:i+17])[1:-1] for i in range(0,len(a),17))
答案 2 :(得分:0)
好像你开始学习python了。我强烈建议调查“for loops”https://docs.python.org/2/tutorial/controlflow.html#for-statements。还可以查看xrange / range,它们很容易用于数字。 xrange和range使用格式范围([start,] end,[[skip]])。 range()和xrange()都包含在开头,但是对于结束是独占的。括号用于表示可选输入。因此,仅提供1个输入实际上意味着范围(0,结束,1)。提供两个输入意味着范围(开始,结束,1)。最后提供3个输入意味着范围(开始,结束,跳过)。还要记住,xrange仅用于循环,因为它实际上不生成列表,xrange被认为是迭代器。
xrange / range的例子:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5,10)
[5, 6, 7, 8, 9]
>>> range(5,10,2)
[5, 7, 9]
为了将变量转换为不同的类型,您可以转换它们。因此,int(n)将任何n转换为整数。同样,str(s)会将s中的任何内容转换为字符串。尝试将变量转换为不可能的变量将引发异常。例如:int(“hellow world!”)自“hello world!”以来不起作用。作为整数没有意义。
# this function will print out n elements per line
# use printNElements(a, 17) to print out 17 at a time
def printNElements(a, n):
for index in xrange(0,len(a),n):
print a[index:index+n]
# this converts all the strings in list a to integers
a = [int(n) for n in a]