[英]Python 3.5.1 Extending a list
sorry to repost (I've just joined stack overflow 30 mins ago).很抱歉重新发布(我刚刚加入堆栈溢出 30 分钟前)。 I don't think I explained in my previous post of my function.
我认为我在之前的函数帖子中没有解释过。
def GetExtendedKeyword(message, newkeyword):
while True:
difference = len(message) - len(newkeyword)
if difference > 0:
newkeyword.extend(newkeyword[:difference]
return newkeyword
elif difference <= 0:
return newkeyword
What I have are two lists, a message and keyword list.我有两个列表,一个消息和关键字列表。 The program calculates the difference between them and if the keyword is shorter than the message list, the program will repeat the keywordlist by that difference.
程序计算它们之间的差异,如果关键字比消息列表短,程序将根据该差异重复关键字列表。
For example the original keywordlist is [0,1,5,2,5]
and the difference is 3, the end result should be [0,1,5,2,5,0,1,5]
.例如,原始
[0,1,5,2,5]
是[0,1,5,2,5]
,差异是 3,最终结果应该是[0,1,5,2,5,0,1,5]
。 The program doesn't like my code when it comes to longer keyword or message lists.当涉及更长的关键字或消息列表时,该程序不喜欢我的代码。 Please help!
请帮忙!
Try it like this像这样试试
l = [0, 1, 5, 4, 2, 9]
l.extend(l[:n]) #extend l with the first n elements of l
This only works for n < len(l) ...这仅适用于 n < len(l) ...
If the amount can be larger than the list length, you can do this:如果数量可以大于列表长度,您可以这样做:
def extend(lst, n):
nfull = n / len(lst) + 1
nrem = n % len(lst)
return lst*nfull+lst[:nrem]
lst = [0,1,5,4,2,9]
print extend(lst, 3)
# [0, 1, 5, 4, 2, 9, 0, 1, 5]
print extend(lst, 7)
# [0, 1, 5, 4, 2, 9, 0, 1, 5, 4, 2, 9, 0]
list.extend(L) Extend the list by appending all the items in the given list;
list.extend(L) 通过附加给定列表中的所有项目来扩展列表; equivalent to a[len(a):] = L.
相当于 a[len(a):] = L。
It's sentence from Python Documentation.这是 Python 文档中的一句话。 I think it is the best place where you should looking for a help.
我认为这是您应该寻求帮助的最佳场所。 Acording to documentation, your code should look like this:
根据文档,您的代码应如下所示:
listOne = [0,1,5,4,2,9]
listOne.extend(listOne[:n])
I wonder to help you.我想帮你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.