gpt4 book ai didi

python - 元组打印元素 if 条件 else 打印范围内的另一个值

转载 作者:太空宇宙 更新时间:2023-11-03 15:11:44 24 4
gpt4 key购买 nike

我有 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,,

请问有什么建议吗?

最佳答案

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

关于python - 元组打印元素 if 条件 else 打印范围内的另一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44164360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com