簡體   English   中英

如何比較Python中不同功能的兩個列表?

[英]how to compare two lists in different functions in Python?

我正在制作 Django web 應用程序,在比較不同功能的兩個不同列表時遇到問題

def test(request,slug):
    n=request.user
    choice=TestOptions.objects.filter(choice=slug).first()
    que=questions.objects.filter(Subject=choice)  
    question=[]
 
    un=['a','b','c','d','e']
    
    for q in que:
        if q not in question:
            question.append(q)
        else:
            continue
    sampling = random.sample(question, 5)
    print("--------------SamPLING111")
    print(sampling)
    print("--------------SamPLING111")
    correctAnswers=[]
    for j in sampling:
          
            correctAnswers.append(j.answer)

    marks(correctAnswers)
    d = dict(zip(un,sampling))
    return render(request,"code/test.html",{'questions':d})

def acceptAnswer(request):
    answers=[]
    if request.method=="POST":
        answers.append(request.POST['a'])
        answers.append(request.POST['b'])
        answers.append(request.POST['c'])
        answers.append(request.POST['d'])
        answers.append(request.POST['e'])

        score(answers)
    return render(request,"code/dub.html")

def marks(correct):
  list1=[]
  l1=correct

def score(and):
  list2=[]
  l2=ans

function 測試通過了一個列表,而 function acceptAnswer 正在通過另一個列表 我的工作是比較這兩個列表

我如何比較l1和l2?

我不是 100% 你想用這些列表做什么,但為了比較它們,我只會返回它們。 這是一個簡單的例子:

def marks(correct):
    list1 = []
    l1 = correct
    return l1

def score(answer):
    list2 = []
    l2 = answer
    return l2
    
numbers = [1,2,3]
numbers2 = [1,2,3]
numbers3 = [3,4,5]

print(marks(numbers) == score(numbers2)) # True
print(marks(numbers2) == score(numbers3)) # False

希望這會有所幫助!

與其繼續發表評論,我想我會在答案中詳細說明,盡管這不是您問題的確切答案,但我認為這是真正的答案。

你真的有兩個問題。 一個是設計問題,即如何使您的程序正常工作,另一個是關於變量 scope 以及如何處理它的實現問題。

我可以在您的個人資料中看到您是一名大學生,並且鑒於代碼的性質,您似乎很可能正在編寫 web 應用程序以用於學習甚至是作業。

如果你在大學之外做這件事,我希望你正在尋找從業者類型的技能,在這種情況下,我建議答案是按照 Django 期望你的方式設計你的應用程序,我會說這會轉化為存儲 state數據庫中的信息。

但是,如果這是一個實驗室,您可能還沒有涵蓋數據庫。 實驗室有時會讓學生做一些愚蠢的事情,因為他們不能同時教所有東西。 所以你的教授可能還不希望你使用數據庫。

在 web 應用程序中,您必須考慮 web 是請求響應,並且您可以從許多不同的來源獲取請求,因此您有 state 管理擔心經典桌面應用程序沒有。 誰應該看到這些測試,誰應該看到標記,這些事情發生的順序是什么? 任何人都應該能夠創建測試嗎? 任何人都應該能夠參加考試嗎? 您可能還不關心,最終您會想要關心會話。 如果人們進行自己的測試,您可以將數據存儲在用戶 session 中,但其他人不會看到這些測試。 通常,存儲這種 state 的正確方法是在數據庫中,您可以根據您對當前請求的了解來訪問它。 如果這是某種基本的介紹應用程序,您的教授可能會對您現在做一些笨拙的事情感到滿意。

暫無
暫無

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

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