Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.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
计算以1、2等开头的数字python 2.7_Python_Python 2.7 - Fatal编程技术网

计算以1、2等开头的数字python 2.7

计算以1、2等开头的数字python 2.7,python,python-2.7,Python,Python 2.7,我知道如何使用str.count(sub[,start[,end]])计算字符的出现次数,但是有没有一种简单的方法来计算字符串中以字符开头的单词 b = "this is 100 111 123 test data" sum(1 for word in b.split() if word.startswith('t')) 2 sum(1 for word in b.split() if word.startswith('1')) 3 工作,但我想我应该在不使用sum或startswith的情况

我知道如何使用str.count(sub[,start[,end]])计算字符的出现次数,但是有没有一种简单的方法来计算字符串中以字符开头的单词

b = "this is 100 111 123 test data"
sum(1 for word in b.split() if word.startswith('t'))
2
sum(1 for word in b.split() if word.startswith('1'))
3

工作,但我想我应该在不使用sum或startswith的情况下进行计数

假设我理解了你的问题(举个例子会很有帮助),你可以尝试以下方法:

 s = 'this is a test'
 target = 't'
 sum([i[0].count(target) for i in s.split()])
 s = 'this is a test'
 sum(1 for word in s.split() if word.startswith('t'))
将告诉您字符串中的2个单词以目标字母('t'开头)


是一个等效但更简洁的解决方案(但存在与评论中指出的问题相同的问题)

我会这样做:

 s = 'this is a test'
 target = 't'
 sum([i[0].count(target) for i in s.split()])
 s = 'this is a test'
 sum(1 for word in s.split() if word.startswith('t'))
如果你的字符串是

instr=“我知道如何使用str.count(sub[,start[,end]])计算字符的出现次数,但是有没有一种简单的方法来计算字符串中以字符开头的单词?”

如果您需要计算字符串中以字符开头的所有单词,比如说
元音=set(“aeiou”)
,那么您可以这样做

>>> sum(1 for c in re.findall("(\w)\w*",instr) if c in vowels)
11
如果你想找到所有以数字开头的单词,那么

sum(1 for c in re.findall("(\d)\w*",instr) if c in vowels)

首先,你需要得到每个开始字母。您可以在文本中使用列表理解:

In [40]: tgt="This is an example text. There are several words starting with letters."

In [41]: fl=[word[0] for word in tgt.split()]

In [42]: fl
Out[42]: ['T', 'i', 'a', 'e', 't', 'T', 'a', 's', 'w', 's', 'w', 'l']
现在数一数

对于单个字母,只需使用生成列表上的计数方法:

In [43]: fl.count('T')
Out[43]: 2
对于所有字母,只需使用集合和字典:

In [50]: d={}

In [51]: for l in set(fl):
            d[l]=fl.count(l) 

In [52]: d
Out[52]: {'T': 2, 'a': 2, 'e': 1, 'i': 1, 'l': 1, 's': 2, 't': 1, 'w': 2}

你能举个例子吗?@malenkiy_scot:你能详细解释一下为什么这不起作用吗?@Abhijit:我想你知道为什么它不起作用。为了其他人的利益:运行
“我说:'这不起作用'”。split()
,第三个单词将是
'This
,因此如果您试图计算以
T
开头的单词,您将错过它。请注意,这是一个完全合法的字符串。@malenkiy_scot:我明白你的意思,但它可能适用于我的简单程序!我认为从正确的方式开始做事很重要:简单的程序往往会随着时间的推移变得复杂。在任何情况下,我只是指出,这里有更多的比眼睛看到的。顺便说一下,@Abhijit的解决方案涵盖了我的情况。啊。。我明白你的意思。。谢谢举个例子(比如你的例子)会很有帮助。