Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.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 如果条件else打印范围内的另一个值,则元组打印元素_Python_Tuples - Fatal编程技术网

Python 如果条件else打印范围内的另一个值,则元组打印元素

Python 如果条件else打印范围内的另一个值,则元组打印元素,python,tuples,Python,Tuples,我有两个列表,一个是嵌套的。我想将其导出为带有条件的txt。每个不同的字母都以。。。i、 e.:“Letter,A”后接元组的第三个元素,否则打印A“,”。存在的条件是,如果元组的第二个元素在var的范围内(从0到5): 到目前为止,我的代码是: bd="Letter," for i in range(0,len(nested_list)-1): if nested_list[i][0]!=nested_list[i+1][0]: bd+="\nLetter,%s,"%

我有两个列表,一个是嵌套的。我想将其导出为带有条件的txt。每个不同的字母都以。。。i、 e.:“Letter,A”后接元组的第三个元素,否则打印A“,”。存在的条件是,如果元组的第二个元素在
var
的范围内(从0到5):

到目前为止,我的代码是:

bd="Letter,"

for i in range(0,len(nested_list)-1):
    if nested_list[i][0]!=nested_list[i+1][0]:
        bd+="\nLetter,%s,"%(nested_list[i][0])
        for j in range(0,var):
            if nested_list[i][1]==j:
                bd+="%s,"%nested_list[i][2]
            else:
                bd+=","
    elif nested_list[i][0]==nested_list[i+1][0]:
        bd+="\n"
        for j in range(0,var):
            if nested_list[i+1][1]==j:
                bd+="%s,"%nested_list[i+1][2]
            else:
                bd+=","

print bd
电流输出:

字母,A,,,0,,,
字母A、、0、、B、、9、、,,
字母,B,,,,,9,,,C,,,,,,,,0,C,,,,,,
字母,C,,,,,,
字母,D,,,9,,,
字母,E,,,0,,
预期产量

字母,A,0,0,,,,
字母B,9,9,9,,
字母C,0,0,0,0
信,D,,9,,,
字母,E,,,0,,
字母,F,,,0,,

有什么建议吗?

如果您的列表总是正确排序,我认为这是itertools的一个很好的使用案例。groupby:

In [14]: from itertools import groupby

In [15]: from operator import itemgetter

In [16]: for k, group in groupby(nested_list, itemgetter(0)):
    ...:     plist = ['']*5
    ...:     for _, idx, val in group:
    ...:         plist[idx-1] = str(val)
    ...:     print("Letter,{},{}".format(k, ','.join(plist)))
    ...:
Letter,A,0,0,,,
Letter,B,9,,9,,
Letter,C,,0,,0,0
Letter,D,,9,,,
Letter,E,,,0,,
Letter,F,,,9,,
In [14]: from itertools import groupby

In [15]: from operator import itemgetter

In [16]: for k, group in groupby(nested_list, itemgetter(0)):
    ...:     plist = ['']*5
    ...:     for _, idx, val in group:
    ...:         plist[idx-1] = str(val)
    ...:     print("Letter,{},{}".format(k, ','.join(plist)))
    ...:
Letter,A,0,0,,,
Letter,B,9,,9,,
Letter,C,,0,,0,0
Letter,D,,9,,,
Letter,E,,,0,,
Letter,F,,,9,,