簡體   English   中英

如何在沒有逗號或括號的情況下打印出元組的內容?

[英]How to print out the contents of a tuple without commas or parantheses?

程序打印出Peter: Number of completed courses: 2 ('Introduction to programming', 3), ('Math', 5)

但我希望它打印時不帶括號或逗號,在我的代碼中我嘗試像*students[name],sep=", ")那樣做,但它只刪除了括號。

def add_student(students,name):
    students[name] = set()

def print_student(students, name):
    
    if name not in students:
        print(f"{name} does not exist in the database")
    else:
        print(f"{name}:")
        print(f"Number of completed courses: {len(students[name])}")
        print(*students[name],sep=', ')
        total_score = 0
        for course in students[name]:   
            total_score += course[1]
        try:
            print(f"average grade : {total_score/len(students[name])}")
        except ZeroDivisionError:
            print("no completed courses")
                 
    
def add_course(students,name, course:tuple):
    if course[1] == 0:
        return 0
    students[name].add(course)
    
    
students = {}
add_student(students,"Ryan")
add_student(students,"Chris")
add_student(students,"Peter")
add_course(students,"Ryan",("Linear Algebra",9))
add_course(students,"Peter",("Math",5))
add_course(students,"Peter",("Program",0))
add_course(students,"Peter", ("Introduction to programming",3))
print_student(students,"Peter")
print_student(students,"Ryan")

這應該是你要找的

for course in students[name]:
    print(f"{course[0]} ({course[1]})")

output:

Introduction to programming (3)
Math (5)

元組總是有序且不可更改的。

當您在代碼下方添加課程時,您將以元組形式提供參數

add_course(students,"Peter",("Program",0))
#                           (tupItem0, tupItem1)  <-- The basic form of a tuple

通過簡單地打印一個元組,您可以獲得整個結構

"('Program',0)"

您可以像列表一樣從元組中獲取數據

foo = ('Program',0)
bar = foo[0] # Bar is now "Program"

在您執行此操作時的程序中:

print(*students[name],sep=', ')

您正在打印整個元組列表。 為了便於解釋,我將按以下方式進行。

outString = ""

for item in students[name]:
  outString += item[0] + ", "

print(outString[:-2])

哪個應該讓你的所有課程都脫離你的數據結構

Math, Introduction to programming

要打印帶有簡單分隔符的元組的內容,請使用 join() ,如下所示:

print(" ".join(my_tuple))

將顯示內容之間有空格。 如果你想讓他們互相“對接”……

print("".join(my_tuple))

使用“漂亮”的逗號分隔符...

print(", ".join(my_tuple))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM