元素打印元素如果条件别打印范围内的另一个值

时间:2017-05-24 16:50:49

标签: python tuples

我有2个列表,1个是嵌套的。我想用条件将它导出到txt。每个不同的字母都以......开头:" Letter,A"然后是其元组的第三个元素存在,否则打印一个","。存在的条件是元组的第二个元素是否在var范围内(从0到5):

var=5

letter=['A','B','C','D','E','F','G','H']
nested_list=[
('A', 1, 0),
('A', 2, 0),
('B', 1, 9),
('B', 3, 9),
('C', 2, 0),
('C', 4, 0),
('C', 5, 0),
('D', 2, 9),
('E', 3, 0),
('F', 3, 9)]

我的代码到目前为止:

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

当前输出:

Letter,A,,,0,,,
Letter,A,,,0,,,B,,,,9,,
Letter,B,,,,9,,C,,,,,0,C,,,,,,
Letter,C,,,,,,
Letter,D,,,9,,,
Letter,E,,,,0,,

预期产出

Letter,A,0,0,,,
Letter,B,9,,9,,
Letter,C,,0,,0,0
Letter,D,,9,,,
Letter,E,,,0,,
Letter,F,,,0,,

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

如果您的列表总是正确排序,我认为这是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,,