Python:如何使用列表中的特定整数?

2024-06-14 22:40:35 发布

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

我对编程相当陌生,我很难弄清楚如何从如下列表中提取特定的数字:

[12, 3, 4]

我怎样才能得到整数并使用它们,比如我想把12和4相乘,或者12和3相乘?我试图找出数字的第一个不同点,例如12-3,然后是3-4。你知道吗

注:我只是用这些数字作为例子,我需要程序做任何整数,用户输入。 谢谢!你知道吗


Tags: 用户程序列表编程数字整数例子不同点
2条回答

您可以通过调用整数在列表中的位置来使用它们。下面是一个加、减和求列表总和的示例:

example = [12, 3, 4]
print(example[0] + example[1]) #15 (12 + 3)
print(example[2] - example[1]) #1 (4 - 3)
print(sum(example)) # 19 (12 + 3 + 4)

好像你想要这样的东西

>>> l = ['12', '3', '4']
>>> def mul(num1, num2):
        if num1 in l and num2 in l:
            return str(int(num1)*int(num2))
        else:
            return 'Number you specified is not present in the list. Please try again'


>>> print(mul(input('Print the num1 : '), input('Print the num2')))
Print the num1 : 1
Print the num2 : 7
Number you specified is not present in the list. Please try again
>>> print(mul(input('Print the num1 : '), input('Print the num2 : ')))
Print the num1 : 3
Print the num2 : 12
36

相关问题 更多 >