python - 在元组中查找元素

标签 python python-3.x tuples

所以我试图让我的计数在元组中看到 yea 时加 1。我的问题是它仍然返回 0。我应该使用 for 循环遍历每个项目吗?

year = input ("enter a year")
count = 0 

t = (("Steve"), ("Carell"), (16, "August", 1962), 
            "Actor", ("Concord", "Massachusetts"))

if year in t:
     count += 1

print(count) 
print (t) #just a check

预期结果 输入:1962 输出:1

最佳答案

由于 t 是元组的元组,您需要遍历每个元组并在该元组中找到年份的出现。在同一个元组中也可能有 2 次年份,因此您需要遍历内部元组中的每个元素。 元组包含整数和字符串,因此我们无法将字符串与整数进行比较,因此在与年份比较之前将元素转换为字符串

year = input ("enter a year")
count = 0 
t = (("Steve"), ("Carell"), (16, "August", 1962), 
            "Actor", ("Concord", "Massachusetts"))
for tup in t:
    for ele in tup:
        if year == str(ele):
            count += 1
print(count)

关于python - 在元组中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51354505/

相关文章:

python - 删除 Pandas 中的单个和一系列列

php - 如果使用中文字符,为什么 php md5() 总是与 python 的 hash.md5() 不同?

python - 如何打印列表中元组平均值的消息

python - 返回由分隔符分隔的字符串列表

python - psutil 中的 cpu-percent 为每个进程返回 0.0

python - 如何在驻留在不同路径的包上使用 mod 选项 "-m"运行 Python3?

python-3.x - 用 Pandas 中另一个数据帧的列替换一个数据帧中的列

c++ - 为什么 std::tuple<int> 不能简单复制?

C++ 可变模板参数和元组迭代

python - 矩阵对象没有属性节点 networkX python