新来的。请查看我的文档字符串,看看我尝试做什么:
def count(data):
""" (list of list of str) -> list of int
Return the numbers of occurrences of strings that end in digits 0, 1, or 2
for each string.
>>> data = [['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']]
>>> count(data)
[1, 1, 2]
"""
num_list = []
num = 0
for sublist in phonemes:
for item in sublist:
if item[-1].isdigit():
num += 1
num_list.append(num)
return num_list
我不知道如何为每个data
sublist
创建一个号码。这甚至是正确的方法吗?任何帮助都会很棒。
答案 0 :(得分:2)
试试这个。
def count(data):
""" (list of list of str) -> list of int
Return the numbers of occurrences of strings that end in digits 0, 1, or 2
for each string.
>>> data = [['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']]
>>> count(data)
[1, 1, 2]
"""
return [ len([item for item in sublist if item[-1].isdigit()]) for sublist in data]
答案 1 :(得分:1)
通过list_comprehension。
>>> data = [['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']]
>>> [len([j for j in i if j[-1] in "012"]) for i in data]
[1, 1, 2]
答案 2 :(得分:0)
我的解决方案:
def count(data):
nums = []
for sub in data:
occur = 0
for i in sub:
if i.endswith(('0', '1', '2')):
occur += 1
nums.append(occur)
return nums
答案 3 :(得分:0)
我认为你有正确的想法,但在完成子列表后你没有将num
重置为0。你现在正在做的是计算所有子列表中的总数0,1,2。你想要的是每个子列表的计数。
在完成整个子列表后,您还必须附加num
。所以你需要将它放在内部for循环体中。
修:
def count(data):
""" (list of list of str) -> list of int
Return the numbers of occurrences of strings that end in digits 0, 1, or 2
for each string.
>>> data = [['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']]
>>> count(data)
[1, 1, 2]
"""
num_list = []
num = 0
for sublist in data:
for item in sublist:
if item[-1] in "012":
num += 1
# item in sublist body is over
# num is now total occurrences of 0,1,2 in sublist
num_list.append(num)
num = 0
return num_list
print count([['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']])
答案 4 :(得分:0)
>>> data = [['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']]
>>> the_lengths = [i for i in map(int, [len([i for i in thelist if i[-1].isdigit()]) for thelist in data])]
>>> the_lengths
[1, 1, 2]