Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.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 如何将list Compherence与method.index()一起使用_Python - Fatal编程技术网

Python 如何将list Compherence与method.index()一起使用

Python 如何将list Compherence与method.index()一起使用,python,Python,如何在列表索引和字符串之间排序 def shuffle(plain_txt,mylist): return ''.join([plain_txt[i] for i in mylist]) def resorting(shuffle_txt,mylist): return shuffle(shuffle_txt, [mylist.index(0)]) print(shuffle('abcd',[2,1,3,0])) print(resorting('cbda

如何在列表索引和字符串之间排序

def shuffle(plain_txt,mylist):
    return ''.join([plain_txt[i] for i in mylist])
     
    
def resorting(shuffle_txt,mylist):
    return shuffle(shuffle_txt, [mylist.index(0)])

print(shuffle('abcd',[2,1,3,0]))
print(resorting('cbda',[2,1,3,0]))

第一个shuffle函数,它将根据列表生成shuffle字符串,例如(str)abcde:(list)[0,4,3,2,1],然后输出是aedcb,因此我创建了函数restring,它将返回字符串序列,使其返回到shuffle之前。

如果
restring()
应该撤销
shuffle()
所做的操作,您需要迭代字符串中的字符和列表中的索引。然后必须将该字符分配给结果字符串中的该索引

def resorting(shuffle_txt, mylist):
    result_list = ['_'] * (max(mylist) + 1)
    for c, index in zip(shuffle_txt, mylist):
        result_list[index] = c
    return ''.join(result_list)

请注意,并非所有洗牌都可以完全反转。如果
mylist
缺少任何索引,则这些字符将不在结果字符串中,并且无法知道它们最初是什么
Restoring()
\uu
放在那些未知的地方。

假设
Restoring()
是为了逆转
shuffle()
的功能,一种简洁的方法是:

def resorting(text, indexes):
    d = {i: c for c, i in zip(text, indexes)}
    return ''.join(d[i] for i in sorted(indexes))

洗牌与排序有什么关系?是的,这些函数的输出应该是什么?我真的不明白你在问什么。您获得的是单个项目,因为您正在将一个列表与单个项目一起传递到
shuffle
insie
restring
。在任何情况下,您都不希望首先在循环中使用
.index
。确切地说,您的代码应该做什么?您是否正在尝试反转
shuffle()
所做的?第一个shuffle函数将根据列表生成shuffle字符串,例如(str)abcde:(list)[0,4,3,2,1],然后输出为aedcb,所以我做了一个函数,这个函数会将字符串序列返回到洗牌之前的状态。但是,你能像洗牌函数一样,用一个lin编码作为回报吗?@grov我认为你不会接受答案,兄弟。你救了我,但是,你能用一个lin编码作为回报吗,比如洗牌功能?因为我的朋友让我用list方法来处理这个问题。index()我不认为你可以,因为它需要在填充结果列表之前初始化它。