我相信我在我的编码中犯了一个错误,我的元组列表是垂直打印的,而不是以正确的方式打印的。有人可以告诉我发生了什么事吗?
这是被问到的问题: 枚举它! 编写一个名为 enum 的函数,它接受一个序列并返回一个二元组列表,每个元组包含索引及其关联项。
这是给出的例子:
>>> enum([45,67,23,34,88,12,90])
[(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]
>> enum('hello')
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
这是我的代码:
def enum(aSequence):
for i in range(7):
b=aSequence[i]
a= [i]
list1 = [a,b]
print (list1)
If following the example input is used this is the result:
[[0], 45]
[[1], 67]
[[2], 23]
[[3], 34]
[[4], 88]
[[5], 12]
[[6], 90]
我想要的结果是: [(0, 45), (1, 67), (2, 23), (3, 34), (4, 88), (5, 12), (6, 90)]
当我去掉 print(list1) 并改用 return list1 时,这就是结果。
[[0], 13]
为什么会这样?
当我把它放到我正在接受辅导的网站上时,会显示“Jack and Jane”这个词,如果是不同的测试,则会显示随机数。我的第二个问题是如何根据参数输入使范围循环适合。我尝试导入数学并随机导入。虽然两者都是短期解决方案,但都不是长期解决方案。
我觉得我对这个问题想得太多了,因为代码就在那里,只是可能缺少基本的基础知识。
最佳答案
这个问题要求您返回一个具有所需结构的列表,所以要小心。您现在正在打印一个。
def enum(aSequence):
list1 = []
for i in range(len(aSequence)):
b = aSequence[i]
a = i
# use append to keep your items in the list to be returned
list1.append((a, b))
return list1
print(enum('hello')) # this should print horizontally like you asked.
关于创建所需列表的最简单答案,枚举函数是您的 friend 。 enumerate 函数将索引的元组和在索引处找到的对象解压为一个可迭代对象。
thing = 'hello there!'
#typical use case for enumerate
for i, item in enumerate(thing):
print(i, item)
所以这是一个可以执行您想要的操作的示例函数...
def enum(iterable):
# must use list() to cast it as an object or else we return a generator object
return list(enumerate(iterable))
enum('hello there!')
关于python - 为什么我的元组列表是垂直的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47359810/