假设我有列表list = [1+3, 4, 3]
.我知道list[0]
等于1+3
,但是我怎么能具体打印出list[0]
中的"+"呢?
我试着做类似的事情
plus = "+"
for plus in list:
takeOut = list.remove(plus)
print(takeOut)
但返回的值是None
请允许我添加一些背景: 我想做一个程序,用户在其中输入一些方程式,计算机吐出结果。如果用户键入1+2 4-3
计算机将打印3 1
。 由于第 0 个值等于1+2
,我想也许如果我删除"+",然后将1
和2
相加,它会给我想要的结果。
这是我的代码文件:
directions = print("Type in a equation")
numbers = [str(x) or int(x) or float(x) for x in input().split()]
print(numbers)
plus = '+'
for plus in numbers:
takeOut = numbers.remove(plus)
print(takeOut)
请注意,这是我做过的第一个Python项目的一部分,所以如果有更好的解决方案,我想知道它。
您错误地将for
循环与if
语句混淆了。如果要检查某个事物是否在列表中,则应使用if
陈述。以下是for
循环的结构:
for temporary_variable in iterable:
# some code
# for example if you loop through ["a", "b", "c"],
# the temporary_variable will first held "a", then "b" on the next iteration and so on.
因此,这就是我更改您的代码以完全匹配您想要的方式:
# Take user's equation as a string
user_eqn = input("Enter your equation: ") # For example, 4+3 will be taken in as "4+3"
# Since it is a string, now it's possible to detect "+"
if "+" in user_eqn:
eqn_nums = user_eqn.split("+") # splitting on "+" will give you a list of numbers. For example, "4+3" will turn in to ["4", "3"]
eqn_nums = [int(num) for num in eqn_nums] # But they are still strings. So convert them to integers using a list comprehension
print(sum(eqn_nums)) # Then use the sum function to calculate the sum of all the values in that list