xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Python list replication All In One

Python list replication All In One

error

For the reference value list, using the list * number does not work as you expected.

# reference value list
letter_lists = [['A', 'B']]
number_lists = [[1, 2]]
strs = letter_lists * 2
nums = number_lists * 2
print('strs =', strs)
print('nums =', nums)
# strs = [['A', 'B'], ['A', 'B']]
# nums = [[1, 2], [1, 2]]

strs[0][1] = "❌"
nums[0][1] = "❌"
print('strs =', strs)
print('nums =', nums)
# strs = [['A', '❌'], ['A', '❌']]
# nums = [[1, '❌'], [1, '❌']]

solution

Using the literal to create a list is OK because it does not reuse any item in the original list.

# literal list
strs = [['A', 'B'], ['A', 'B']]
nums = [[1, 2], [1, 2]]
print('strs =', strs)
print('nums =', nums)
# strs = [['A', 'B'], ['A', 'B']]
# nums = [[1, 2], [1, 2]]

strs[0][1] = "✅"
nums[0][1] = "✅"
print('strs =', strs)
print('nums =', nums)
# strs = [['A', '✅'], ['A', 'B']]
# nums = [[1, '✅'], [1, 2]]

For the primary value list, use the list * number is OK

# primary value list
letter_list = ['A', 'B']
number_list = [1, 2]
strs = letter_list * 2
nums = number_list * 2
print('strs =', strs)
print('nums =', nums)
# strs = ['A', 'B', 'A', 'B']
# nums = [1, 2, 1, 2]

strs[1] = "✅"
nums[1] = "✅"
print('strs =', strs)
print('nums =', nums)
# strs = ['A', '✅', 'A', 'B']
# nums = [1, '✅', 1, 2]

The reason is that you do not have a deep understanding of the list data type when using list * number to create a new copy of the list in Python.

image

demos

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

Python 3

https://developers.google.com/edu/python/lists?hl=zh-cn

https://www.geeksforgeeks.org/literals-in-python/

https://realpython.com/python-data-types/

https://blog.enterprisedna.co/how-to-multiply-lists-in-python/

https://drbeane.github.io/python/pages/collections/list_operations.html

refs

https://docs.python.org/3/library/stdtypes.html

https://stackoverflow.com/questions/77094468/changing-the-value-of-a-subarray-via-a-link/77095147#77095147



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-09-13 18:07  xgqfrms  阅读(5)  评论(0编辑  收藏  举报