簡體   English   中英

如何在python中找到字符串的最大值和最小值?

[英]How to find the max and min from a string in python?

這是我目前的計划。 它正在輸出不正確的最大值和最小值。 我的if語句缺少什么?

def palin():
  max = 0
  min = 50
  numbers = "23","3","4","6","10"
  for x in numbers:

    if x>max:
      max=x
    if x<min:
      min=x

  print max
  print min

當你進行字符串比較或嘗試使用min()max()和字符串時,你實際上是按字母順序排序:

>>> sorted(numbers)
['10', '23', '3', '4', '6']

這就是為什么許多依賴於位置比較的內置 Python函數支持key參數:

>>> numbers
('23', '3', '4', '6', '10')
>>> sorted(numbers, key=int)
['3', '4', '6', '10', '23']
>>> min(numbers, key=int)
'3'
>>> max(numbers, key=int)
'23'

你的號碼是字符串。 首先將它們轉換為整數:

numbers = [int(num) for num in numbers]

def palin():
  max = 0
  min = 50
  numbers = "23","3","4","6","10"
  numbers = [int(num) for num in numbers]
  for x in numbers:

    if x>max:
      max=x
    if x<min:
      min=x

  print max
  print min

python中的許多常見操作都有相關的built-in函數或相關的模塊/包。

在這種情況下, max()min()是你的朋友。

str_numbers = ("23", "3", "4", "6", "10")
numbers = [int(n) for n in str_numbers ]  # convert to integers
max_value = max(numbers)
min_value = min(numbers)

max()min()也支持使用生成器表達式,因此您可以在函數本身中進行轉換:

str_numbers = ("23", "3", "4", "6", "10")
max_value = max(int(n) for n in str_numbers)
min_value = min(int(n) for n in str_numbers)

如果你已經安裝了Numpy,你可以輕松獲得結果。

import numpy as np

numbers = ["23","3","4","6","10"]
numbers = [int(n) for n in numbers]
numpy_array = np.array(numbers)
print 'Max:  ', numpy_array.max()
print 'Min:  ', numpy_array.min()
print 'Mean: ', numpy_array.mean()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM