python str文本等于dict的名称

2024-09-24 06:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

你能告诉我为什么它不工作吗

代码:

DictModels = {'DDR3 4GB 1333Mhz' : 4}
Text = 'DDR3 4GB 1333Mhz'
for j in range(len(DictModels)):
      Klopo = str(list(DictModels)[j])
      if  Klopo is Text:
        Text = 'it work'

Tags: 代码textinforlenifisrange
3条回答

您正在进行对象比较

if Klopo is Text:

你应该比较一下这个值

if Klopo == Text:

此外,您可能还想打印“它起作用”

print("it Works")

嗯,可能提供适当的代码(前面是一个示例)

DictModels = {}
    NrChild = request.POST.get('NrPop')
    for i in range(int(NrChild)):
        if i==0:
            Text = (request.POST.get('GB')) + "GB"
            title = request.POST.get('ChoiceFieldComputer')
            Text += " " + SpecRamAdd.objects.get(id=int(title)).Ram + " "
            DictModels[Text] = int(request.POST.get('NrStack'))
        else:
            j = 0
            numberTake = str(i+1)
            Text = str(request.POST.get('GB' + numberTake)) + "GB"
            title = request.POST.get('ChoiceFieldComputer' + numberTake)
            Text += " " + SpecRamAdd.objects.get(id=int(title)).Ram
            for j in range(len(DictModels)):
                if  str(list(DictModels)[j]) == Text:
                    DictModels.values()[j] += int(request.POST.get('NrStack' + str(numberTake)))
                else:
                    DictModels[Text] = int(request.POST.get('NrStack' + str(numberTake)))
    Text = str(DictModels)
    TextMail = {
        'ShowText': Text,
    }
    return render(request, 'Order.html', TextMail)

我选择电脑型号和需要多少内存。然后我想显示段落(“<;p>;”),其中包含闸板的名称和件数。有时两个不同的型号有相同的名称Rams,所以我只想增加件数。所以我不想这样:

DDR3 1666 Mhz x3
DDR3 1333 Mhz x2
DDR3 1333 Mhz x1

我想这样:

DDR3 1666 Mhz x3
DDR3 1333 Mhz x3

在本段中:str(list(DictModels)[j])是与变量文本相同的文本。那么为什么它不起作用呢?我早些时候用c#编写了代码

in运算符是否是替代迭代的好选择

DictModels = {'DDR3 4GB 1333Mhz' : 4}
Text = 'DDR3 4GB 1333Mhz'
if Text in DictModels:
    print('it worked')

此运算符将检查变量是否位于字典的键中,而不是在整个字典中进行迭代

相关问题 更多 >