守着星空守着你
让我们假设这一点。你有一个这样的列表:a = ["3,2", "4,25"] 当然,您可以访问以下项目:print(a[0]) # 3,2print(a[0][0]) # 3print(a[0][2]) # 2print(a[1][0]) # 4print(a[1][2]) # 2但是如果你有一个两位数的数字,你会怎么做?你用逗号分割字符串。print(a[0].split(',')[0]) #3print(a[0].split(',')[1]) #2print(a[1].split(',')[0]) #4print(a[1].split(',')[1]) #25然后,当您比较它们时,不要忘记将字符串 (3或2) 转换为数字 (整数),以便您可以比较它们。这称为铸造。for element in a: if int(element.split(',')[0]) > int(element.split(',')[1]): print('first is bigger') else: print('second is bigger')
慕标5832272
对于数组中的每个元素元素是一个字符串。字符串有方法split。我用逗号将字符串分成几部分。例子: string = "1,2" result = string.split(',') # Here I split by comma print(result) # ['1', '2']Python 有一个很好的解包可迭代元素的机制:result = ['1', '2']left, right = result# Same as # left = result[0]# right = result[1]print(left) # '1'print(right) # '2'# Now variables left and right store strings# If you want to make integers:left = int(left)right = int(right)array = ["3,2", "4,5","6,7"]for element in array: left_num, right_num = element.split(',') left_num = int(left_num) right_num = int(right_num) print(left_num, right_num)