简体   繁体   English

无法在打印功能中运行列表

[英]Can't run through a list in print function

I'm a beginner to python.我是python的初学者。 I've written this code but I can't execute the for loop inside the print function to iterate through the list of marks:我已经编写了这段代码,但我无法在 print 函数中执行 for 循环来遍历标记列表:

class student:
    def __init__(self, name, age, iden, lMark):
        self.name=name
        self.age=age
        self.iden=iden
        self.lMark=lMark
    def printAve(self, obj):
        for i in obj.lMark:
            res+=i
        av=res/len(lMark)
        return av
    def disInfo(self, obj):
        print("the name is: ",obj.name)
        print("the age is: ",obj.age)
        print("the identity is: ",obj.iden)
        print("the marks are: ", for i in lMark:
             print(i))
    def addStudent(self, n, a, i, l):
        ob=student(n,a,i,l)
        ls.append(ob)
        return true
    def searchStudent(self, _val):
        for i in len(ls):
            if ls[i]==_val:
                return i

ls=[]
s=student("Paul", 23,14, list(15,16,17,20,12))
bool added = s.add("Van", 20, 12, list(12,18,14,16))
if added==True:
    print("Student added successfully")
for i in range(ls.__len__())
    s.disInfo(ls[i])

Can someone help me to solve this problem and explain me how to do?有人可以帮我解决这个问题并解释我该怎么做吗?

from statistics import mean

# classes are named LikeThis
# constants named LIKE_THIS
# other variables should be named like_this
# hungarian notation is not used in Python
class Student:
    # instead of a global variable named ls,
    # I'm using a class variable with a clear name instead
    all_students = []
    def __init__(self, name, age, iden, marks):
        self.name = name
        self.age = age
        self.iden = iden
        self.marks = marks
    def printAve(self):
        # you don't need to pass two arguments when you're only operating on a single object
        # you don't need to reinvent the wheel, see the import statement above
        return mean(self.marks)
    def disInfo(self):
        print("the name is:", self.name)
        print("the age is:", self.age)
        print("the identity is:", self.iden)
        # you can't put a statement inside of an expression
        # I'm guessing you want the marks all on the same line?
        # the *args notation can pass any iterable as multiple arguments
        print("the marks are:", *self.marks)
    # this makes more sense as a classmethod
    # clear variable names are important!
    @classmethod
    def addStudent(cls, name, age, iden, marks):
        # I'm using cls instead of Student here, so you can subclass Student if you so desire
        # (for example HonorStudent), and then HonorStudent.addStudent would create an HonerStudent
        # instead of a plain Student object
        cls.all_students.append(cls(name, age, iden, marks))
        # note the capital letter!
        return True
    # again, this should be a classmethod
    @classmethod
    def searchStudent(cls, student):
        # use standard methods!
        try:
            return cls.all_students.index(student)
        except ValueError:
            return None

# the literal syntax for lists in Python is `[1, 2, 3]`, _not_ `list(1, 2, 3)`.
# it also makes more sense to use Student.addStudent here, because just calling Student() doesn't add it
# to the list (although you could do that in __init__ if you always want to add them to the list)
Student.addStudent("Paul", 23, 14, [15, 16, 17, 20, 12])
# in Python, type annotations are optional, and don't look like they do in C or Java
# you also used `add` instead of `addStudent` here!
added: bool = Student.addStudent("Van", 20, 12, [12,18,14,16])
# don't need == True, that's redundant for a boolean value 
if added:
    print("Student added successfully")

# never call `x.__len__()` instead of `len(x)`
# (almost) never use `for i in range(len(x))` instead of `for item in x`
for student in Student.all_students:
    student.disInfo()

First I answer your initial question, you can print a list in different ways, here are some of them.首先我回答你最初的问题,你可以用不同的方式打印一个列表,这里有一些。 You can iterate through it with a for loop and print every element on a different line:您可以使用 for 循环遍历它并在不同的行上打印每个元素:

for elem in self.lMark:
    print(elem)

You can also append all values to a string and separate them by a character or something.您还可以将所有值附加到一个字符串中,并用字符或其他东西将它们分开。 (Note: There will be a trailing space at the end.) (注意:末尾会有一个尾随空格。)

myString = ""
for elem in self.lMark:
    myString = myString + str(elem) + " "
print(myString)

Better is this by doing it with strings-join method and a short version of the container iteration:通过使用 strings-join 方法和容器迭代的简短版本来做到这一点更好:

", ".join([str(i) for i in self.lMark])

There were some more issues in the code example.代码示例中还有一些问题。 Here is a running version of the script:这是脚本的运行版本:

class Student:
    def __init__(self, name, age, iden, lMark):
        self.name=name
        self.age=age
        self.iden=iden
        self.lMark=lMark

    def printAve(self, obj):
        for i in obj.lMark:
            res+=i
        av=res/len(self.lMark)
        return av

    def disInfo(self):
        print("the name is: ",self.name)
        print("the age is: ",self.age)
        print("the identity is: ",self.iden)
        print("the marks are: ", ", ".join([str(i) for i in self.lMark]))


class StudentList:
    def __init__(self):
        self.__list_of_students = []

    def add(self, s):
        self.__list_of_students.append(s)
        return True
    
    def get(self):
        return self.__list_of_students

    def search(self, name):
        for s in self.__list_of_students:
            if s.name == name:
                return s
        
        return None

ls = StudentList()
s=Student("Paul", 23,14, [15,16,17,20,12])
ls.add(s)
added = ls.add(Student("Van", 20, 12, [12,18,14,16]))

if added:
    print("Student added successfully")

search_name1 = "Paula"
search_name2 = "Van"

if ls.search(search_name1):
    print(search_name1, "is part of the list!")
else:
    print("There is no", search_name1)


if ls.search(search_name2):
    print(search_name2, "is part of the list!")
else:
    print("There is no", search_name2)

for student in ls.get():
    student.disInfo()
    print("-"*10)

I would suggest to separate the list of students and the students to two different classes as shown in the code above.我建议将学生名单和学生名单分成两个不同的班级,如上面的代码所示。

您可以使用*运算符解压缩您的列表:

print("the marks are: ", *lMark)

You can't put a bare for loop in the argument list to print , and of course the embedded print doesn't return what it prints.您不能在参数列表中放置一个裸for循环来print ,当然嵌入的print不会return它打印的内容。 What you can do is你能做的是

print("the marks are:", ", ".join(lMark))

or perhaps也许

print("the marks are:", *lMark)

(Also, I believe you mean obj.lMark .) (另外,我相信你的意思是obj.lMark 。)

To reiterate, if you call some code in the argument to print , that code should evaluate to the text you want print to produce;重申一下,如果您在print的参数中调用一些代码,则该代码应评估为您希望print生成的文本; not do printing on its own.不要自己打印。 For example,例如,

def pi()
    return 3.141592653589793  # not print(3.141592653589793)

def adjective(arg):
    if arg > 100:
        return "big"  # not print("big")
    else:
        return "small"  # not print("small")

print(str(pi()), "is", adjective(pi()))

Notice how each function call returns something, and the caller does something with the returned value.注意每个函数调用如何返回一些东西,调用者如何用返回的值做一些事情。

Try setting this as a function.尝试将其设置为函数。 ie IE

def quantity():
    for i in lMark:
        print(i)

Then,然后,

def disInfo(self, obj):
    print("the name is: ",obj.name)
    print("the age is: ",obj.age)
    print("the identity is: ",obj.iden)
    print("the marks are: ", + quantity)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过列表运行 function? - How to run function through a list? 我如何制作一个函数来通过 2 个特定步骤(Python)打印列表的值 - How can i make a function which will print the values of the list through 2 specific steps(Python) 为什么我不能运行只有打印功能的 .py 文件? - Why can't I run a .py file that only has a print function? 递归功能不打印列表 - Recursive function doesn't print list 在代码搜索完列表并且找不到列表中的单词从而答复错误后,如何打印? - How do you print after the code is done searching through the list and it can't find the word in the list so it replies error? 如何通过函数运行日期字符串列表并将每个项目的结果作为一个串联字符串返回? - How can I run a list of date strings through a function and return the results of each item as one concatonated string? 打印功能无法继续打印完整列表 - Print function won't print the complete list before moving on Python 3-我无法使用.strip()函数成功打印我的排序列表 - Python 3 - I can't print my sorted list using the .strip() function successfully 无法重新创建范围 function 以在否定步骤中打印列表。 它还打印一个额外的数字 - Can't get recreated range function to print a list in a negative step. It also prints an extra number 无法在python中打印列表值 - Can't Print a list value in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM