使用功能创建列表

发布于 2025-02-04 18:38:26 字数 437 浏览 1 评论 0原文

import csv

def readLevel(filename,listname):
    listname=[]
    with open(filename, "r") as element:
        csv_reader = csv.reader(element)
        listname = list(csv_reader)

readLevel('level001.csv','LEVEL_001')
readLevel('level002.csv','LEVEL_002')

print(LEVEL_001)
print(LEVEL_002)

错误:未定义的名称“ Level_001”

我试图创建一个接收文件名 + listName的函数,从而从文件(文件名)中读取数据并将其列入列表(listName)。 创建列表,但没有正确的名称。 有正确的方法吗?

import csv

def readLevel(filename,listname):
    listname=[]
    with open(filename, "r") as element:
        csv_reader = csv.reader(element)
        listname = list(csv_reader)

readLevel('level001.csv','LEVEL_001')
readLevel('level002.csv','LEVEL_002')

print(LEVEL_001)
print(LEVEL_002)

Error: name 'LEVEL_001' is not defined

I'm trying to create a function that receives a filename + listname and thus reads the data from a file (filename) and put it in a list (listname).
A list is created but not with the correct name.
Is there a correct way to do this ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

宛菡 2025-02-11 18:38:26

字符串值'Level_001'与称为level_001的变量不同。

您应该返回在函数中创建的值,然后在调用代码中分配一个变量名称:

import csv

def readLevel(filename):
    with open(filename, "r") as element:
        return list(csv.reader(element))


LEVEL_001 = readLevel('level001.csv')
LEVEL_002 = readLevel('level002.csv')

print(LEVEL_001)
print(LEVEL_002)

The string value 'LEVEL_001' is not the same thing as a variable called LEVEL_001.

Instead of trying to pass a variable name as an argument to the function, you should return the value that you create in your function and then assign it a variable name in the calling code:

import csv

def readLevel(filename):
    with open(filename, "r") as element:
        return list(csv.reader(element))


LEVEL_001 = readLevel('level001.csv')
LEVEL_002 = readLevel('level002.csv')

print(LEVEL_001)
print(LEVEL_002)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文