Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python编写代码的较短方法_Python - Fatal编程技术网

用Python编写代码的较短方法

用Python编写代码的较短方法,python,Python,我是Python初学者。下面的代码正是我想要的。但它看起来有点像垃圾堆,因为它有三个循环。有人能告诉我更聪明/更短的方法来实现它吗?可以是单个函数,也可以是循环的并行化 def getWordListAndCounts(text): words = [] for t in text: for tt in t: for ttt in (re.split("\s+", str(tt))): words.append(str(ttt))

我是Python初学者。下面的代码正是我想要的。但它看起来有点像垃圾堆,因为它有三个循环。有人能告诉我更聪明/更短的方法来实现它吗?可以是单个函数,也可以是循环的并行化

def getWordListAndCounts(text):
  words = []  
  for t in text:
      for tt in t:
        for ttt in (re.split("\s+", str(tt))):
            words.append(str(ttt))
  return Counter(words) 

text = [['I like Apple' , 'I also like Google']]
getWordListAndCounts(text)

首先删除冗余列表(这将降低列表理解的级别):

因为并没有必要将临时结果存储在列表中,所以生成器是更可取和有效的方法。 检查此单线方法:

text = ['I like Apple' , 'I also like Google']
print Counter(str(ttt) for t in text for ttt in (re.split("\s+", str(t))))
  • 使用有意义的变量名。t、 tt和ttt不能帮助代码可读。
    为什么不使用“文本中的短语”然后使用“短语中的单词”
  • 为什么要使用双编码字符串?除非你在阅读时已经是这种格式,否则我建议你不要这样做
    如果
    text
    [“我喜欢苹果”,“我也喜欢谷歌”]
    而不是
    [[“我喜欢苹果”,“我也喜欢谷歌”]
    ,你就可以少做一个循环。无论如何,为什么要使用双括号?实际上,文本来自另一种方法>>def get_Text(评论,分数):Text=[]Text.append([r[0]。如果r[1]==str(分数)],则评论中r的下限();return text你可能会在这里得到更好的结果:我投票决定把这个问题作为离题题来结束,因为它属于主题
    import re
    from collections import Counter
    
    def getWordListAndCounts(text):
        return Counter(re.split('\s+', str([' '.join(x) for x in text][0])))
    
    text = [['I like Apple' , 'I also like Google']]
    print getWordListAndCounts(text)