我有一个python元组,其元素实际上是句子。我想比较每个元素的第一个字母,如果它们是小写的,我将它连接到前一个元素。如果他们不是我加入第一个元素。 例如,如果我有:
tuple1 = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence', 'which is incomplete.')
我的结果应该是:
tuple1 = ('Traditionally, companies have been communicating with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence which is incomplete.')
这是我的工作代码:
i=0
while i<(len(tuple1)-1):
if tuple1[i+1][0].islower():
tuple1[i] + " " + tuple[i+1]
i+=1
我怎样才能做到这一点?感谢
答案 0 :(得分:3)
您可以使用itertools.groupby
:
import itertools
tuple1 = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence', 'which is incomplete.')
new_data = tuple(' '.join(i[-1] for i in b) for _, b in itertools.groupby(enumerate(tuple1), key=lambda x:x[-1][0].islower() or tuple1[x[0]+1][0].islower() if x[0]+1 < len(tuple1) else True))
输出:
('Traditionally, companies have been communicating with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence which is incomplete.')
答案 1 :(得分:3)
希望这能满足您的需求。我没有使用任何外部模块就做到了。
look_these_up
答案 2 :(得分:3)
正如第一条评论所述,元组是不可变的。使用列表可能更容易,如果你真的需要一个元组,你可以在之后将结果列表转换为一个。
return
应该照顾它。您需要最后一行来清除temp_list。