简体   繁体   English

仅当 python 中的两个元素都为真时,我将如何检查和 append?

[英]How will I check and append only if both elements are true in python?

#I want to append the tuple, only if both the elements are two-digit. #我想要 append 元组,前提是两个元素都是两位数。 I have tried to use all function, but ended up with many errors.我尝试使用所有 function,但最终出现许多错误。 Please help me to get the desired output请帮我获得所需的 output

print("The original list is : " + str(test_list))

K = 2
res=[]


for sub in test_list:
    for ele in sub:
        if len(str(ele))==K:
            res.append(sub)
print("The Extracted tuples : " + str(tuple(res)))

# Output that I want enter image description here # Output 我想在这里输入图像描述

#As you can see the output that I want, help to write the proper code for that, Thanks in Advance #如您所见,我想要的 output,帮助编写正确的代码,提前致谢

You can use the else statement of a for loop.您可以使用 for 循环的else语句。 it is useful to check for the condition that is not met:检查不满足的条件很有用:

original_list = [(54, 2), (34,55), (222,23), (12,45), (78,)]
# append tuples if both values have 2 digits
new_list = []
for item in original_list:
    for i in item:
        if len(str(i)) != 2:
            break
    else:
        new_list.append(item)
print(new_list)
#[(34, 55), (12, 45), (78,)]

You want to include the tuple in the final list if all the elements of the tuple are two-digit;如果元组的所有元素都是两位数,则您希望将元组包含在最终列表中; your loop will append the tuple once for each element that is two-digit.您的循环将为每个两位数的元素 append 元组一次。

This will do what you're looking for:这将满足您的需求:

print("The original list is :", test_list)
print("The extracted tuples :", [t for t in test_list if all(9 < i < 100 for i in t)])

you probably have some issues with question format, read up on markdown please.您可能对问题格式有一些疑问,请阅读 markdown。 Plus, this question is rather specific and doesn't really help others if they read this page, so i think stackoverflow people don't really like this.另外,这个问题相当具体,如果他们阅读这个页面并不能真正帮助其他人,所以我认为 stackoverflow 的人并不真正喜欢这个。

Anyways, in your code, you are checking if either of the element is 2 digits, then append.无论如何,在您的代码中,您正在检查任何一个元素是否为 2 位数字,然后是 append。 But, the problemt requirement askes you to check both elements of the tuple.但是,问题要求要求您检查元组的两个元素。

for item1, item2 in test_list: #foreach item in list, grab first and second item
    if len(str(item1)) == 2 and len(str(item2)) == 2: 
        #append to result iff both items have length of 2
        res.append((item1, item2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM