Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.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_Python 2.7_List - Fatal编程技术网

python插入函数列表理解

python插入函数列表理解,python,python-2.7,list,Python,Python 2.7,List,我试图使用列表理解在一行中编写一个4-5行代码。但是这里的问题是我不能使用insert函数,所以我想知道是否有解决方法 原始代码: def order(text): text = text.split() for x in text: for y in x: if y in ('1','2','3','4','5','6','7','8','9'): final.insert(int(y)-1, x)

我试图使用列表理解在一行中编写一个4-5行代码。但是这里的问题是我不能使用insert函数,所以我想知道是否有解决方法

原始代码:

def order(text):
    text = text.split()
    for x in text:
        for y in x:
            if y in ('1','2','3','4','5','6','7','8','9'):
                final.insert(int(y)-1, x)

    return final
到目前为止,我所尝试的:

return [insert(int(y)-1, x) for x in text.split() for y in x if y in ('1','2','3','4','5','6','7','8','9')]
但我面临以下错误:
名称错误:未定义全局名称“插入”

我尝试使用insert,因为任务是使用每个单词中出现的数字重新排列列表中的项目


例如,我有
is2-Th1is T4est 3a
作为输入,结果应该是:
Th1is-is2-3a T4est
而不是使用列表理解,您应该在键函数中使用这些数字对列表进行排序,例如,使用正则表达式提取数字

>>> import re
>>> s = "is2 Th1is T4est 3a"
>>> p = re.compile("\d+")
>>> sorted(s.split(), key=lambda x: int(p.search(x).group()))
['Th1is', 'is2', '3a', 'T4est']

您可以通过将代码拆分为几个简单的函数来实现您的原始想法,并创建一个适当大小的列表(填入
None
s)以保留单词的最终顺序:

def extract_number(text):
    return int(''.join(c for c in text if c.isdigit()))

def order(text):
    words = text.split()
    result = [None] * len(words)

    for word in words:
        result[extract_number(word) - 1] = word

    return ' '.join(result)
您也可以使用
sorted()
在一行中完成此操作:


没有插入函数
final.insert
是一种方法,您不会显示
final
实际上是什么(大概是一个列表)。还要注意的是,您不应该对副作用使用列表理解-
list.insert
返回
None
,我怀疑您是否需要.1的列表。什么是
最终版
?2.列表理解会动态地构建列表,因此您现在考虑的是
insert
ing,因为还没有创建任何列表。3.是的,没有名为
insert
的标准函数,你为什么希望它存在呢?@ForceBru Final是我在原始代码中使用的列表。对于这种列表理解,有没有办法运行该表达式?与“self-insert”类似,可以用元组中的
if y(“123456789”)
安全地替换
if y,以节省空间并提高可读性。您可以将元组保存为一个值:
values=tuple(“123456789”)
,然后执行
if y in values
,这样元组就不会在每次到达该
if
语句时重建。@IdontReallywolf,您想在哪里插入内容?当你运行一个列表时,还没有列表存在,没有地方插入它。西方最快的枪!愚蠢的我,我还在为和你完全相同的代码写解释。做得好!您还可以使用
int(filter(str.isdigit,x))
代替正则表达式。如果还想支持Python 3,则必须使用
'.join()
def extract_number(text):
    return int(''.join(c for c in text if c.isdigit()))

def order(text):
    return ' '.join(sorted(text.split(), key=extract_number))