python - 'if' 中的计数方法不起作用 - python

标签 python

我不明白,我正在尝试数这个列表中的 2,当它是这样的时:

hand=['D2', 'H5', 'S2', 'SK', 'CJ', 'H7', 'CQ', 'H9', 'D10', 'CK']
f=''.join(hand)
count2=f.count('2')
print count2

它工作得很好,它打印我 2 作为 2 在列表中的次数。 但是当我把它放在 if 它不起作用时:

def same_rank(hand, n):
    if hand.count('2')>n:
        print hand.count('2')
    else:
        print 'bite me'



hand=['D2', 'H5', 'S2', 'SK', 'CJ', 'H7', 'CQ', 'H9', 'D10', 'CK']
f=''.join(hand)
n=raw_input('Give n ')
print same_rank(hand,n)

如果用户给出 n=1,那么它应该打印 2,因为数字 2 在列表中出现了两次,我希望它比 1 多!那么为什么它不返回呢?

最佳答案

raw_input() 返回一个字符串;字符串始终排在数字之后,因此 2 > '1' 始终为 False:

>>> 2 > '1'
False

首先将您的输入转换为整数:

n = int(raw_input('Give n '))

如果您使用 Python 3,则会出现异常:

>>> 2 > '1'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() > str()

因为 Python 3 已经不再为任意类型提供相对顺序。

接下来,你不传入f,而是传入hand,列表:

>>> hand.count('2')
0
>>> f
'D2H5S2SKCJH7CQH9D10CK'
>>> f.count('2')
2

您可能想传递后者,否则您的函数将无法工作。

关于python - 'if' 中的计数方法不起作用 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23696679/

相关文章:

python - 如何将列表中字典集中的每个元素组合到另一组字典列表中?

java - 使用 Android 应用程序将文件上传到我的 Google API 项目

python - Django 中的 CSS 不更新

python - Tkinter create_image() 保留 PNG 透明度,但 Button(image) 不保留

python - 美丽汤 : Fetched all the links on a webpage how to navigate through them without selenium?

python - IPython Notebook session 中的多个目录和/或子目录?

python - Sphinx 自动文档与 Django 1.4

Python - Pandas - 如何创建增量为 0.01 秒的日期时间序列?

python - 从 Python 脚本获取当前目录的父目录

python - 从 "Today"或 "Yesterday"开始计时和在 Python 中计时的最佳方法是什么?