在Python中的嵌套列表上循环。打印单个字母

发布于 2025-01-24 09:02:55 字数 757 浏览 0 评论 0原文

我正在尝试将每个元素从列表中删除,但是由于某种原因,它正在打印列表中每个元素的每个字符。我该如何纠正?

我当前的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

捎一片雪花 2025-01-31 09:02:55

您可以将多维列表更扁平到单维列表,其中具有以下递归实现,该递归实现使用isInstance函数来检查变量是否为类型列表,允许我们正确地使用字符串弄平列表:

myList = ['apple',['banana', 'blueberry'],'strawberry','']
def flatten(l):
    out = []
    for i in l:
        if isinstance(i,list): 
            out += flatten(i)
        else: 
            out.append(i)
    return out
print(flatten(myList))

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:

myList = ['apple',['banana', 'blueberry'],'strawberry','']
def flatten(l):
    out = []
    for i in l:
        if isinstance(i,list): 
            out += flatten(i)
        else: 
            out.append(i)
    return out
print(flatten(myList))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文