处理清单清单

时间:2019-02-23 17:03:28

标签: python python-3.x list

我有一个大约有60000个字符的列表。 我正在使用的软件包仅接受超过999个字符的列表... 因此,对于此示例,我必须运行函数60000/999 = 61次。

以下是列表的示例:

liste=[ 'item1', 'item2', 'item3', 'item4'...]

这里是问题,随着时间的流逝,字符数可能会越来越少,因此,我必须考虑列表的长度。

这是我要使用的代码:

ids = function(liste)
for id in ids:
   print(id)

我想一个主意应该是做一个列表列表,第一个大列表包括每个列表的999个字符的61个列表,然后循环:

for lists in list: 
    ids = function(lists)
    for id in ids:
        print(id)

有人有更好的主意和/或知道如何根据第一个大列表的长度创建列表吗?

2 个答案:

答案 0 :(得分:2)

听起来您想用较短的块处理较长的列表。您无需将列表预处理为简短列表的列表。这是一个将列表分成子列表的生成器。根据需要进行调整:

# Quick way to create a long list of numbers.
# I used a size that isn't a multiple of the chunk size to show that it doesn't matter.
items = list(range(105))

# Function to return smaller lists of the larger list.
def chunk(items,n):
    for i in range(0,len(items),n):
        yield items[i:i+n]

# Break the larger list into length 10 lists.
for subitems in chunk(items,10):
    print(subitems) # process as you want...

输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69]
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
[100, 101, 102, 103, 104]

因此您的代码应类似于:

for sublist in chunk(liste,999):
    taxids = accession.taxid(sublist)
    for tax in taxids:
        print(tax)

答案 1 :(得分:0)

您似乎是Python新手。在python中创建列表时,无需为该列表指定长度。当可以创建字符串列表并且仍将其用作字符串列表时,为什么要创建列表列表?因此,您不必考虑长度。

对于您提出的问题,我不太清楚,如果我错了,请纠正我。另外,我假设s3 = boto3.resource('s3') content_object = s3.Object('test', 'sample_json.txt') file_content = content_object.get()['Body'].read().decode('utf-8') json_content = json.loads(file_content) print(json_content['anything']) # Use your desired JSON Key for your value 是一个用户制作的函数(由您制作),用于向列表中添加新元素。

以下是已经定义的accession

的代码
liste

以下是您想直接接受输入的代码

# I am assuming the list  'liste' is already defined
taxids = []
for i in liste:
    taxids.append(list(i))
print(taxids)

让我知道是否有帮助!