在元组中查找元素

时间:2018-07-16 04:14:06

标签: python python-3.x tuples

因此,我尝试让我的计数在元组中看到是就加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

5 个答案:

答案 0 :(得分:3)

由于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)

答案 1 :(得分:1)

您也可以尝试以下代码。

def get_count(t, year):
    count = 0

    for item in t:
        if type(item) is str:
            if year in item:
                count += 1
        elif type(item) is tuple:
                if int(year) in item or year in item:
                    count += 1
        elif type(item) is int:
            if int(year) == item:
                count += 1

    return count

# START
if __name__ == "__main__":
    # INPUT 1
    year = input("Enter a year")

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

    count = get_count(t, year)
    print(count)

    # INPUT 2
    year = input("Enter a year")

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

    count = get_count(t, year)
    print(count) # 2

    # INPUT 3
    year = input("Enter a year")

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

    count = get_count(t, year)
    print(count) # 4

答案 2 :(得分:1)

通过列表理解用一行代码解决它怎么办?

year = input ("enter a year")
t = (("Steve"), ("Carell"), (16, "August", 1962), 
    "Actor", ("Concord", "Massachusetts"))
print(len([j for k in t for j in k if j == year]))

答案 3 :(得分:0)

如果它深深地嵌入另一个嵌套中怎么办?建议使用正则表达式。您可以使用re.search

import re

year = input ("enter a year: ")
count = 0 
t = (("Steve"), ("Carell"), (16, "August", 1962), 
            "Actor", ("Concord", "Massachusetts"))
if re.search(year,str(t)):
      count += 1
print(count)

答案 4 :(得分:-1)

您介意尝试此操作吗?

count = 0
year = 1962
tuples = (("Steve"), ("Carell"), (16, "August", 1962),
            "Actor", ("Concord", "Massachusetts"))

for tuple in tuples:
    if str(year) in str(tuple):
       count += 1

print(count)
相关问题