Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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,下面的列表是ppm文件的一部分。这三个数字是红、绿、蓝。下面的列表是更大的列表名称num的一部分 num=list below [..... [155, 155, 155],...[100, 100, 100]... [222, 222, 222]....] for pixels in num: for rgb in pixels: print([255 - rgb for rbg in pixels]) 运行此代码时,您将获得 [100,

下面的列表是ppm文件的一部分。这三个数字是红、绿、蓝。下面的列表是更大的列表名称num的一部分

num=list below  
    [..... [155, 155, 155],...[100, 100, 100]...
    [222, 222, 222]....] 

for pixels in num:
     for rgb in pixels:
          print([255 - rgb for rbg in pixels])
运行此代码时,您将获得

[100, 100, 100]
[100, 100, 100]
[100, 100, 100]
[33, 33, 33]
[33, 33, 33]
[33, 33, 33]
如何使它只打印其中一个,而不是三个相同的

[100, 100, 100]
[33, 33, 33]

去掉你的内环

>>> nums = [[155, 155, 155],
...         [222, 222, 222]]

>>> for pixels in nums:
...    print([255 - rgb for rgb in pixels])

>>> [100, 100, 100]
>>> [33, 33, 33]
编辑:要将
打印
输出到文件:

f = open('path/to/file', 'w')
for pixels in nums:
    f.write(', '.join(str(255 - rgb) for rgb in pixels) +'\n')
f.close()

从外观上看,您有一个不需要的循环:

for pixels in num:
     for rgb in pixels:
          print([255 - rgb for rgb in pixels])
应该是:

for pixels in num:
      print([255 - rgb for rgb in pixels])

否则,您将为每个像素打印列表3次,为该像素中的每个元素打印一次。

前两个列表的名称是什么?请提供更多上下文。列表理解仅生成一个列表。作业标记已过时。
f=open('path/to/file','w')
每行仍有[222222222]。。。如何删除它们。[],括号中。。最后一个问题