Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_Concatenation_String Concatenation - Fatal编程技术网

在Python中连接列表中的不完整集合

在Python中连接列表中的不完整集合,python,list,concatenation,string-concatenation,Python,List,Concatenation,String Concatenation,我有一个包含完整和不完整句子的列表。完整的句子以、?或结尾。如何循环列表中的元素并连接不完整的句子? 比如说, 输入: 期望输出: 下面是一个使用collections.defaultdict的暴力方法 from collections import defaultdict myList = ['My first','sentence is incomplete.','Hold on.','Is the second complete?', 'The third','mig

我有一个包含完整和不完整句子的列表。完整的句子以
结尾。如何循环列表中的元素并连接不完整的句子?
比如说,

输入: 期望输出:
下面是一个使用
collections.defaultdict
的暴力方法

from collections import defaultdict

myList = ['My first','sentence is incomplete.','Hold on.','Is the second complete?',
          'The third','might not be!','Thanks.','Really appreciate.']

d = defaultdict(list)

idx = 0
for j in myList:
    d[idx].append(j)
    if any(j.endswith(k) for k in ('.', '!', '?')):
        idx += 1

sentences = [' '.join(v) for _, v in sorted(d.items())]
结果:

['My first sentence is incomplete.',
 'Hold on.',
 'Is the second complete?',
 'The third might not be!',
 'Thanks.',
 'Really appreciate.']

连接不完整的句子是最简单的部分,只需使用“+”符号连接句子。例如,使用myList[0]+myList[1]获得“我的第一个句子不完整”。您应该从列表中删除使用过的元素,以避免以后出现任何问题。要验证要添加哪些,应使用如下while循环:

while (myList!=[]):
    index=0
    if myList[index][-1]=="." or myList[index][-1]=="?" or myList[index][-1]=="!" : #checks if the last element of the string is a . ? or !
        #make a function to concatenate the list elements from myList[0] to myList[index],and delete said elements from the original list, remember to reset index to 0 and repeaat process

你试过什么?这并不像你想象的那么简单。与此类似:@cᴏʟᴅsᴘᴇᴇᴅ 我试过很多建议,但结果不一致。如果是简单的,我就不会寻求帮助。@TheSolider,我在看到副本之前发布了一个解决方案。碰巧,我将解决方案保留在这里,因为这是一种不同的方法,我太懒了,无法将其适应dup。@jpp感谢您提供的解决方案。对于一个完全不同的问题,这是一种完全不同的方法。
['My first sentence is incomplete.',
 'Hold on.',
 'Is the second complete?',
 'The third might not be!',
 'Thanks.',
 'Really appreciate.']
while (myList!=[]):
    index=0
    if myList[index][-1]=="." or myList[index][-1]=="?" or myList[index][-1]=="!" : #checks if the last element of the string is a . ? or !
        #make a function to concatenate the list elements from myList[0] to myList[index],and delete said elements from the original list, remember to reset index to 0 and repeaat process