gpt4 book ai didi

python - 在 Python 中比较和连接元组

转载 作者:太空狗 更新时间:2023-10-30 02:01:31 24 4
gpt4 key购买 nike

我有一个 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

我怎样才能做到这一点?谢谢

最佳答案

你可以使用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.')

关于python - 在 Python 中比较和连接元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48934473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com