【发布时间】:2017-11-19 00:50:15
【问题描述】:
我正在尝试创建一个采用二维列表并返回字典的函数。我想知道是否有比我写的更有效的方法(例如列表理解/ itertools?)我对python比较陌生,并且已经阅读了一些关于列表理解和itertools doc的示例(https://stackoverflow.com/questions/16548668/iterating-over-a-2-dimensional-python-list)但不能似乎将它实现到这块代码中。
任何帮助将不胜感激。谢谢!
def listToDict(self, lstInputs):
dictOutput = dict()
rows = len(lstInputs)
cols = len(lstInputs[0])
if rows == 2:
for x in range(rows):
if lstInputs[0][x] is not None:
if lstInputs[1][x] is not None:
dictOutput[lstInputs[0][x].strip()] = lstInputs[1][x].strip()
else:
dictOutput[lstInputs[0][x].strip()] = lstInputs[1][x]
elif cols == 2:
for x in range(rows):
if lstInputs[x][0] is not None:
if lstInputs[x][1] is not None:
dictOutput[lstInputs[x][0].strip()] = lstInputs[x][1].strip()
else:
dictOutput[lstInputs[x][0].strip()] = lstInputs[x][1]
else:
pass
return dictOutput
【问题讨论】:
-
你能提供一个示例列表吗?
-
@JanZeiseweis 嗨!感谢您的回复!我在docs.python.org/3/library/itertools.html#itertools.zip_longest 和jmduke.com/posts/a-gentle-introduction-to-itertools 上阅读了一些示例,但似乎找不到可以帮助解决此问题的1 个示例。如果我要链接列表,我想不出在循环时如何将键值对分配给字典
-
请举例输入输出。
-
我实际上是在询问您想要转换为字典的示例列表。
-
这是一个已经回答的交叉引用。 stackoverflow.com/questions/30387014/…
标签: python list python-3.x loops dictionary