Python字符串拆分联接4
上面有一个我有问题的代码。我应该得到的输出是:Python字符串拆分联接4,python,string,list,join,Python,String,List,Join,上面有一个我有问题的代码。我应该得到的输出是: import re string = "is2 Thi1s T4est 3a" def order(sentence): res = '' count = 1 list = sentence.split() for i in list: for i in list: a = re.findall('\d+', i) if a == [str(coun
import re
string = "is2 Thi1s T4est 3a"
def order(sentence):
res = ''
count = 1
list = sentence.split()
for i in list:
for i in list:
a = re.findall('\d+', i)
if a == [str(count)]:
res += " ".join(i)
count += 1
print(res)
order(string)
相反,我得到的是正确的顺序,但空格在错误的位置:
"Thi1s is2 3a T4est"
你知道如何使用这个代码概念吗 您正在连接每个单词的字符:
"T h i 1 si s 23 aT 4 e s t"
您希望将您的单词收集到一个列表中,并加入该列表:
我使用了更详细、更清晰的变量名。我还删除了列表
变量;如果可以避免,请不要将list
用作变量名,因为这会掩盖内置的list
名称
您实现的可以归结为O(N^2)(二次时间)排序。您可以使用内置的sort()
函数将其转换为O(NlogN);您将提取数字并按其整数值排序:
def order(sentence):
number_words = []
count = 1
words = sentence.split()
for word in words:
for word in words:
matches = re.findall('\d+', word)
if matches == [str(count)]:
number_words.append(word)
count += 1
result = ' '.join(number_words)
print(result)
这与您的版本稍有不同,因为它只查看第一个(连续的)数字,它不关心数字的顺序,并且会断开没有数字的单词。它还使用返回
将结果提供给调用者,而不是打印。只需使用print(订单(字符串))
打印返回值
如果假设单词从1开始连续编号,则可以按O(N)时间偶数对其排序:
def order(sentence):
digit = re.compile(r'\d+')
return ' '.join(
sorted(sentence.split(),
key=lambda w: int(digit.search(w).group())))
这是通过创建一个长度相同的列表来实现的,然后使用每个单词的数字将单词放入正确的索引中(减1,因为Python列表从0开始,而不是1)。我认为这个错误只是由于滥用join()。您希望连接当前已排序的字符串
i
只是一个标记,因此只需将其添加到字符串的末尾。代码未经测试
def order(sentence):
digit = re.compile(r'\d+')
words = sentence.split()
result = [None] * len(words)
for word in words:
index = int(digit.search(word).group())
result[index - 1] = word
return ' '.join(result)
你为什么要使用
”。那么加入(i)
?你用空格连接了一个单词的所有字符。谢谢你,伙计,它现在起作用了,这是我对如何连接的误解。这看起来像是在连接。这留下了一个空格作为开始。@Aaken00:我不认为你误解了连接的工作原理,你只是在错误的顺序上使用了它。@MartijnPieters很好。是的,也许调用res=res[1:][/code>就可以了?我记不住语法了。@Tuan333:好吧,规范的方法是把res
列成一个列表,使用res.append(i)
,然后在最后使用'.join(res)
。如果你想要更高的复杂度,你也可以很容易地把它列成O(N):-)直观地说,我不会像那样实例化结果,我会使用列表comp。我离开电脑有一段时间了,所以在我忘记之前,如果我们想象这个列表很大,那么你用result=[None]*len(words)
这样做有什么原因吗?好好利用lambda+1@roganjosh:对此,列表理解速度较慢;只要所乘列表的内容是不可变的,或者希望生成的列表引用相同的对象,就可以使用乘法。
def order(sentence):
digit = re.compile(r'\d+')
words = sentence.split()
result = [None] * len(words)
for word in words:
index = int(digit.search(word).group())
result[index - 1] = word
return ' '.join(result)
import re
string = "is2 Thi1s T4est 3a"
def order(sentence):
res = ''
count = 1
list = sentence.split()
for i in list:
for i in list:
a = re.findall('\d+', i)
if a == [str(count)]:
res = res + " " + i # your bug here
count += 1
print(res)
order(string)