在Python上比较元组和int

时间:2016-10-20 16:46:21

标签: python

我正在比较Python中元组的组件来查找bigest和最小的元组,但是我的代码只返回了touple的两个最新组件,我不明白为什么:

numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
numbers2=numbers.split()
numbers2=tuple(numbers2)
i=0
gran=numbers2[0]
petit=numbers2[0]
for i in range (len(numbers2)):
    if numbers2[i]>gran:
    gran=numbers2[i]
print(gran)
j=0
for j in range (len(numbers2)):
    if numbers[j]<petit:
    petit=numbers2[j]
print(petit)
resultat= gran+" "+petit
print(resultat)

我得到了#6; 6 -6&#34;作为回报。有帮助吗?感谢

4 个答案:

答案 0 :(得分:2)

其他人已经提到需要将项目转换为整数。我还想提一下,minmax函数可用。

>>> numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
>>> numbers_tuple=tuple(int(i) for i in numbers.split())
>>> min(numbers_tuple)
-214
>>> max(numbers_tuple)
542

这也避免了像许多以前的答案那样创建初始列表,但是在tuple()实例化中使用生成器表达式而不是列表理解。

答案 1 :(得分:1)

将分割后的字符串转换为整数,然后再将其转换为元组。

numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
numbers2=[int(x) for x in numbers.split()]
numbers2=tuple(numbers2)
...

您还可以将这两个操作合并为一行。

numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
numbers2=tuple([int(x) for x in numbers.split()])
...

答案 2 :(得分:0)

你的元组是一个字符串元组,而不是一个整数元组。你需要将你的元组转换为整数元组:

numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
numbers2=numbers.split()
numbers2 = [int(i) for i in numbers2] # convert tuple of strs to tuple of ints

完全正常工作的程序:

numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
numbers2=numbers.split()
numbers2 = [int(i) for i in numbers2] # convert tuple of strs to tuple of ints
numbers2=tuple(numbers2)
i=0
gran=numbers2[0]
petit=numbers2[0]
for i in range (len(numbers2)):
    if numbers2[i]>gran:
        gran=numbers2[i]
print(gran)
j=0
for j in range (len(numbers2)):
    if numbers2[j]<petit:
        petit=numbers2[j]
print(petit)
resultat= str(gran)+" "+str(petit)
print(resultat)

输出:

542
-214
542 -214
>>> 

我应该注意,你的程序写得比你现在的程序简单得多:

numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"

# convert the numbers string to a tuple of integers
num_lst = tuple([int(i) for i in numbers.split()])

# take a guess and say the
# highest and lowest are both
# the first element in num_lst
lowest = num_lst[0]
highest = num_lst[0]

# iterate through the
# num_lst. No need to
# initizalize i beforehand
for i in num_lst:
    # if we find a higher number
    # then our guess of the highest
    # number, reassign highest to that number
    if i > highest:
        highest = i
    # if we find a lower number
    # then our guess of the lowest
    # number, reassign lowest to that number
    elif i < lowest:
        lowest = i

# print the highest and lowest number
print("Highest:", highest, " Lowest:", lowest)

答案 3 :(得分:0)

这可以归结为简单的两行:

numbers=tuple([int (a) for a in "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6".split()])
print(str(max(numbers)) + ' ' + str(min(numbers)))

这些值最初是作为字符串插入的,因此必须强制转换为整数才能进行比较。打印结果时,如果您希望将它们打印在同一行中,并且中间有空格,则可以将数字转换回字符串

更优雅的方法是不使用字符串来表示数字,而是使用数组:

numbers=tuple([4, 5, 29, 54, 4, 0, -214, 542, -64, 1, -3, 6, -6])
print(str(max(numbers)) + ' ' + str(min(numbers)))