在Python中的嵌套列表上循环。打印单个字母
我正在尝试将每个元素从列表中删除,但是由于某种原因,它正在打印列表中每个元素的每个字符。我该如何纠正?
我当前的代码:
import pandas as pd
myList = ["apple", ["banana", "blueberry"], "strawberry", ""]
myNames = ["Peter", "John", "Sally", "Craig"]
for x, y in zip(myNames, myList):
decision = {"name": x, "fruit": y, "data": pd.DataFrame()}
globals()[x] = decision
for d, v in zip(myNames, myList):
if len(v) > 1:
for i in range(len(v)):
print(v[i])
else:
print(v)
d["data"] = v
现在,输出是:
A
P
P
L
E
我不想要这个。我希望Apple
成为一个元素,并浏览else
子句。如果子句是['Banana','Blueberry']
我该怎么做?
I am trying to get each elements out of the list, but for some reason, it is printing out each individual characters of each element within the list. How would I correct this?
My current code:
import pandas as pd
myList = ["apple", ["banana", "blueberry"], "strawberry", ""]
myNames = ["Peter", "John", "Sally", "Craig"]
for x, y in zip(myNames, myList):
decision = {"name": x, "fruit": y, "data": pd.DataFrame()}
globals()[x] = decision
for d, v in zip(myNames, myList):
if len(v) > 1:
for i in range(len(v)):
print(v[i])
else:
print(v)
d["data"] = v
Right now, it's output is:
A
P
P
L
E
I do not want this. I want apple
to be a single element and go through the else
clause. The only element that should go through the if
clause is ['banana','blueberry']
How would I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将多维列表更扁平到单维列表,其中具有以下递归实现,该递归实现使用
isInstance
函数来检查变量是否为类型列表,允许我们正确地使用字符串弄平列表:You can flatten a multidimensional list to a single-dimensional list with the following recursive implementation that uses
isinstance
function to check whether a variable is of type list, allowing us to flatten lists with strings correctly: