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

在Python中附加到列表

在Python中附加到列表,python,python-2.7,Python,Python 2.7,我试图不断地向列表中添加值;保留这些值,直到程序退出 import sha1 def stored_hash(hash): hashes = [] hash_extend = [hash] hashes.extend(hash_extend) return hashes loop = 1 while loop == 1: data= raw_input('Enter text to hash: ') hash = sha1.run(data

我试图不断地向列表中添加值;保留这些值,直到程序退出

import sha1


def stored_hash(hash):
    hashes = [] 
    hash_extend = [hash]
    hashes.extend(hash_extend)
    return hashes

loop = 1
while loop == 1:
    data= raw_input('Enter text to hash: ')
    hash = sha1.run(data)
    store = stored_hash(hash)
    print store
我有一个名为sha1的程序,它创建输入文本的散列。我希望将该散列存储在上面的散列列表中,并且能够在每次循环完成时添加更多的散列,以便我的列表越来越大

我该怎么办?我有点不明白为什么我不能在列表的末尾附加一个值,然后用现有的哈希值打印出整个列表。无论循环完成多少次,我现在只得到一个散列值


是否需要将其设置为全局列表?

只需将列表作为参数传入即可:

import sha1

def stored_hash(store, hash):
    store.append(hash)

store = []
loop = 1
while loop == 1:
    data = raw_input('Enter text to hash: ')
    hash = sha1.run(data)
    stored_hash(store, hash)
    print store
def stored_hash(hash, prev_hash):
    prev_hash.extend(hash)
    return prev_hash

此行不会将变量哈希的内容转换为列表-它会将其中的所有内容放入新的新列表中:

hash_extend = [hash]
这就是你真正想要的:

hash_extend = list(hash)
这样,变量哈希的内容将转换为一个列表。例如:

>>> ls = [1,2,3]
>>> [ls]
[[1, 2, 3]]
>>> list(ls)
[1, 2, 3]
另外,如果您只需要扩展列表,您可以跳过对列表的转换,因为我假设变量hash已经包含一个iterable:

def stored_hash(hash):
    hashes = []
    hashes.extend(hash)
    return hashes
但是,这不会在每次调用函数时扩展列表。为此,请将其作为第二个参数传递给函数:

import sha1

def stored_hash(store, hash):
    store.append(hash)

store = []
loop = 1
while loop == 1:
    data = raw_input('Enter text to hash: ')
    hash = sha1.run(data)
    stored_hash(store, hash)
    print store
def stored_hash(hash, prev_hash):
    prev_hash.extend(hash)
    return prev_hash
这样称呼它:

store = stored_hash(hash, store)

可能是,您可以全局声明哈希列表

global hashes
hashes = []

编写上述部分将使其在您的程序中在全球范围内可用。

ahhh这很有效,正是我想要的。我甚至没想过把它当作一个论点。非常感谢。我会回答这个的让我。