![](/img/trans.png)
[英]Pygame: This spritesheet code works on another project, but not this one. Why?
[英]Extend a list with another one. Why this behaviour?
我有一個 2 個元素列表,我想用另一個元素來擴展它。 在 Jupyter 中玩弄我發現了這種我無法理解的奇怪行為。
# this is my first list
columnslist=['app','SUM']
['app','SUM']
# it is going to be extended with the values A and B
columnslist.extend(['A','B'])
['app','SUM','A','B']
# It is possible to make a list out of a string in this way
print(list('AB'))
['A','B']
# I realise that list('AB')= ['A','B']
This works:
columnslist.extend(list('AB'))
# but the following does not work:
mytext='this is a text to be split'
columnslist.extend(mytext.split())
為什么呢? 謝謝
首先,使用關鍵字作為變量是不好的做法。 第二件事它不能使用擴展功能,因為它是一個字典對象。
編輯:我希望我猜對了,您想在帶有空格的字符串中提取字母嗎? 那么你可以嘗試以下代碼
>>>my_list= ["A","B"]
>>>test_str = "This is a text"
>>>my_list.extend(list("".join(test_str.split())))
['A','B','T', 'h', 'i', 's', 'i', 's', 'a', 't', 'e', 'x', 't']
文本以空格分隔,您可以在這里使用.split
。 .split
轉換列表中的字符串。
columnslist.extend(mytext.split(' '))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.