2016-12-03 85 views
-1
if match: 
    occur=0 
    for item in tweets: 
     if candidate in item: 
      popular=item[4]+item[5] 
      occur+=popular 
      famous.append(occur) 
return occur 

的名单,我得到10161只。也因为这个功能是有办法,我可以按号码列表,并与候选人按排序号字典与元组的Python

+0

和你期望或希望从你的功能得到什么结果? – Copperfield

+0

@Copperfield所以如果日期是两个日期之间,IM goanna补充说,看到谁是著名的代码(通过添加最后两个数字),并打印出与人从最大到最小著名 – CAVS

+0

...好,但名单不回答我的问题,这个函数应该做什么?返回满足条件的人的名单? – Copperfield

回答

2

的修改很简单,首先你需要创建一个空的列表,其中结果将被保留,然后返回一个列表在for循环中,您需要检查条件是否已满足,并将该元素添加到列表中(如果有),最后返回该列表。我也选择一些更有意义的变量名

def famous(data_tweet, lower, higher): 
    result=[] 
    for person, tweets in data_tweet.items(): 
     if all(lower <= tw[2] <= higher for tw in tweets): 
      result.append(person) 
    return result 

这可以减少与使用listcomprehension

def famous(data_tweet, lower, higher): 
    return [person for person, tweets in data_tweet.items() if all(lower <= tw[2] <= higher for tw in tweets)] 

一点点(注意相似)

在这两种情况下

结果

>>> famous(tweet,1470000000,1480000000) 
['b', 'a'] 
>>> 

至于你是不是允许使用all,那么它应该做的老派风格,即使用标志,它是一个变量,它会告诉我们,如果条件满足与否

def famous(data_tweet, lower, higher): 
    result=[] 
    for person, tweets in data_tweet.items(): 
     is_valid = True 
     for tw in tweets: 
      if not (lower <= tw[2] <= higher): 
       is_valid = False 
       break 
     if is_valid: 
      result.append(person) 
    return result 

我们在这里首先假设条件满足,那么我们检查是有效真的,如果不是我们改变我们的标志为false,并打破循环,因为没有更多的理由继续进行进一步的检查,这是基本上是all做为你。之后,根据标志的价值,我们将该人员追加到列表中。

(如果您还没有允许使用break或者,也别担心,只是将其删除,这不会影响功能)


关于计数的东西

result=[] 
for person in tweet: 
    count = 0 
    for tw in tweet[person]: 
     count += tw[4] + tw[5] 
    result.append(count) 
+0

copperfield是否有一种方法可以不使用全部? – CAVS

+0

是的,但是这可以归结为重写'all',为什么你不想使用它? – Copperfield

+0

即使是语言功能标准集的一部分,我也不允许使用 – CAVS