2012-03-17 21 views
0

我在Python中遇到问题。在if语句中自动递增 - “number”

我该如何完全自动地递增 - 这个if语句中存在的“数字”?

一个理解我的例子。我有这种情况

 
def name1: 
    if (dictionary[class.methodclass()][constant - 1] == dictionary[class.methodclass()][constant - 2] == dictionary[class.methodclass()][constant - 3] == ldictionary[class.methodclass()][constant - 4] == dictionary[class.methodclass()][constant - 5]): 
     blablabla 

def name2: 
    if (dictionary[class.methodclass()][constant - 1] == dictionary[class.methodclass()][constant - 2] == dictionary[class.methodclass()][constant - 3] == ldictionary[class.methodclass()][constant - 4]): 
     blabla 

def name3: 
    if (dictionary[class.methodclass()][constant - 1] == dictionary[class.methodclass()][constant - 2] == dictionary[class.methodclass()][constant - 3]): 
     blabla

我重复相同的代码,所以如何避免这种情况?

谢谢

编辑:我有一个正常的dictonary像

dictonary = {"Element": ["Key1", "Key2"]}

我想有一个确认我“KEY1” ==“密钥2”的情况下工作的一个周期。

+0

是否使用ldictionary打字错误? – 2012-03-17 16:03:34

+0

告诉我们更多关于你的数据和你为什么写这些功能。这些名字并没有告诉我们你想要解决的问题。 – 2012-03-17 16:12:07

+0

我有一个正常的dictonary = {“Element”:[“Key1”,“Key2”]} 我想要一个确认我使用“Key1”==“Key2”情况的循环。 – 2012-03-17 16:20:47

回答

1

这是一个办法:

if all ([ dictionary[class.methodclass()][constant - 1] == 
      dictionary[class.methodclass()][ noConstant] 
      for noConstant in range(constant - 2, constant - 6, -1) ] 
     ): 
    blablabla 
+0

谢谢你的回答。这种方式返回两个单个字符串的结果,重复另一个字符串。所以我有一个结果像写: if([dictionary [class.methodclass()] [constant - 1] == dictionary == class [class.methodclass()] [constant -2]): blablabla if([字典[class.methodclass()] [constant - 1] == dictionary [class.methodclass()] [constant -3]): blablabla 等等...所以输出不等于我想看的。 – 2012-03-17 16:26:31

+0

@SniperWolf,检查第二个字典索引:'[noConstant]'。在我的回答中,我比较了所有其他字典出现的情况,另请参阅'all' python函数。很抱歉解释你的评论。我不明白你在说什么。 – danihp 2012-03-17 16:30:06

+0

是的,对不起我的英语不好。我重新尝试解决方案,并为我工作得非常好。谢谢,我通过你发现了一个新的有用的解决方案。 再次,非常感谢! – 2012-03-17 16:54:22

0

的核心目标,我可以从你的代码概括为:判断是否在列表中的某一节的值都是一样的。

按照这个逻辑,我们可以写一个函数来归档:

def is_list_section_repeated(li, start, end): 
    section = li[start:end] 
    if section.count(section[0]) == len(section): 
     return True 
    return False 

有了这个功能您的代码可能是:

def name1: 
    if is_list_section_repeated(dictionary[class.methodclass()], constant - 5, constant - 1): 
     blablabla 

def name2: 
    if is_list_section_repeated(dictionary[class.methodclass()], constant - 4, constant - 1): 
     blablabla 

.... 

由于情况是一种对于最常见的情况,我认为编写一个函数来处理它特别是使用棘手的技巧可能会使代码不清楚,难以阅读:P

0

您的任务分为两部分:

a)您有几个重复同一复杂测试的功能。

解决方案:如果测试足够复杂,则将其分解为一个单独的函数,该函数返回True或False。在你的每个nameN函数中使用它。

b)你有一个测试,检查一系列元素是否都是相同的。在编辑中使用简单版本:给定字典键列表,检查所有值是否相同。

解决方案:抓取所有的价值观,形成了一套,并检查其大小:

tocheck = [ "Key1", "Key2" ] 
values = set(mydict[k] for k in tocheck) 
if len(values) == 1: 
    print "equal" 
else: 
    print "unequal" 

可以适应同样的方法你原来的代码:写一个理解(或任何其他类型的循环),其收集所有你正在比较的值。如果你这么做了,那么建立一个封装这种测试的简单函数是值得的。