如何使用可变字典长度同时遍历字典项?
How can you iterate through dict items at the same time with variable dict length?
我想遍历具有 n
个键和值的字典。
例如:
d = {0:"batched data", 1:"batched data", 2:"batched data", ..., n: "batched data"}
由于批处理的数据是pytorch DataLoader形式,它不可索引只能迭代。
因此,如何一次遍历所有 dict 批处理数据:
我在想 zip 可能会有用,但我不确定当长度可变时如何计算它。
例如如果n=3
:
for index, data in enumerate(zip(d[0],d[1],d[2])):
会起作用,但是如何将其推广到任意数量的字典元素?
查看命令的输出:
for index, data in enumerate(zip(d[0],d[1],d[2])):
print("{} -> {}".format(index, data))
在我看来,这将处理一般情况:
d = {0:"batched data", 1:"batched data", 2:"batched data", 3: "batched data"}
for index, data in enumerate(zip(*d.values())):
print("{} -> {}".format(index, data))
输出:
0 -> ('b', 'b', 'b', 'b')
1 -> ('a', 'a', 'a', 'a')
2 -> ('t', 't', 't', 't')
3 -> ('c', 'c', 'c', 'c')
4 -> ('h', 'h', 'h', 'h')
5 -> ('e', 'e', 'e', 'e')
6 -> ('d', 'd', 'd', 'd')
7 -> (' ', ' ', ' ', ' ')
8 -> ('d', 'd', 'd', 'd')
9 -> ('a', 'a', 'a', 'a')
10 -> ('t', 't', 't', 't')
11 -> ('a', 'a', 'a', 'a')
我想遍历具有 n
个键和值的字典。
例如:
d = {0:"batched data", 1:"batched data", 2:"batched data", ..., n: "batched data"}
由于批处理的数据是pytorch DataLoader形式,它不可索引只能迭代。
因此,如何一次遍历所有 dict 批处理数据:
我在想 zip 可能会有用,但我不确定当长度可变时如何计算它。
例如如果n=3
:
for index, data in enumerate(zip(d[0],d[1],d[2])):
会起作用,但是如何将其推广到任意数量的字典元素?
查看命令的输出:
for index, data in enumerate(zip(d[0],d[1],d[2])):
print("{} -> {}".format(index, data))
在我看来,这将处理一般情况:
d = {0:"batched data", 1:"batched data", 2:"batched data", 3: "batched data"}
for index, data in enumerate(zip(*d.values())):
print("{} -> {}".format(index, data))
输出:
0 -> ('b', 'b', 'b', 'b')
1 -> ('a', 'a', 'a', 'a')
2 -> ('t', 't', 't', 't')
3 -> ('c', 'c', 'c', 'c')
4 -> ('h', 'h', 'h', 'h')
5 -> ('e', 'e', 'e', 'e')
6 -> ('d', 'd', 'd', 'd')
7 -> (' ', ' ', ' ', ' ')
8 -> ('d', 'd', 'd', 'd')
9 -> ('a', 'a', 'a', 'a')
10 -> ('t', 't', 't', 't')
11 -> ('a', 'a', 'a', 'a')