Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表理解,如果切片超过列表边界,则执行此操作_Python_List_List Comprehension - Fatal编程技术网

Python 列表理解,如果切片超过列表边界,则执行此操作

Python 列表理解,如果切片超过列表边界,则执行此操作,python,list,list-comprehension,Python,List,List Comprehension,我对python相当陌生,在以下代码段中使用了列表理解: while offset < len(list) s = ['{:04x}'.format(i) for i in list[offset:offset+16]] do stuff with s offset += 16 代码段在列表中循环,并以格式化的方式将最多16个元素添加到s,然后将16添加到偏移量值,以获得下一个16,直到看到所有元素为止。这在我未简化的代码中起作用,但我想在片段超过列表大小时使用占

我对python相当陌生,在以下代码段中使用了列表理解:

while offset < len(list)
    s = ['{:04x}'.format(i) for i in list[offset:offset+16]]
    do stuff with s
    offset += 16

代码段在列表中循环,并以格式化的方式将最多16个元素添加到s,然后将16添加到偏移量值,以获得下一个16,直到看到所有元素为止。这在我未简化的代码中起作用,但我想在片段超过列表大小时使用占位符,而不是让它停止向s添加元素。我知道我可以用一个完整的for循环来做这件事,但我想试着在理解中做这件事,以保持这一行的简洁。我想我在理解中需要一个if/else,但似乎无法确定需要什么条件。

您可以动态地将切片块填充到固定大小。例如:

while offset < len(l):
    s = ['{:04x}'.format(i) for i in l[offset:offset + 16] + [0] * max(0, offset + 16 - len(l))]
    offset += 16
    # Do something

将切片与包含占位符的列表连接起来-因此,当切片结束时,将获取占位符,并向循环中添加一个具有所需范围最终大小的二级迭代器,以限制从第一部分生成的项:

s = ['{:04x}'.format(i) for i, j in in  zip(list[offset:offset+16] + ([placeholder] * 16)  , range(16) ) ]

最简单的方法是使用某种石斑鱼来给你块。-模块提供以下功能:

from itertools import zip_longest  # or izip_longest in Python2

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)
有了这个功能,你可以这样做:

lst = list(range(20))

for group in grouper(lst, n=8, fillvalue=0):
    print(['{:04x}'.format(i) for i in group])
产生此输出:

['0000', '0001', '0002', '0003', '0004', '0005', '0006', '0007']
['0008', '0009', '000a', '000b', '000c', '000d', '000e', '000f']
['0010', '0011', '0012', '0013', '0000', '0000', '0000', '0000']

你为什么这么做?这个过程背后的基本原理是什么?记住,聪明的代码通常不如实用的代码简洁。你能给出一个你想在这种情况下执行的动作的例子吗?代码的目的是从一个输入文件中创建一个数据表。我从工作副本中删除了很多,因此占位符值将填充末尾的空白单元格,并保持所有行的长度为16。理解的目的只是探索如何/如果可以做到。永远不要调用变量列表!list是列表构造函数。而且,由于循环的迭代次数是已知的,对于0范围内的偏移量,lenlist,16:将是一个更合适的循环。我只为伪代码调用了变量列表,在工作代码中没有调用它。感谢您的帮助,我甚至没有考虑修改列表本身来实现这一点。
lst = list(range(20))

for group in grouper(lst, n=8, fillvalue=0):
    print(['{:04x}'.format(i) for i in group])
['0000', '0001', '0002', '0003', '0004', '0005', '0006', '0007']
['0008', '0009', '000a', '000b', '000c', '000d', '000e', '000f']
['0010', '0011', '0012', '0013', '0000', '0000', '0000', '0000']