Python List Comprehensions All In One
Python List Comprehensions All In One
列表推导式
print([i for i in range(10)])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print([i for i in range(20) if i%2 == 0])
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
nums = [1, 2, 3, 4]
arr = [i for i in range(len(nums))]
print("arr =", arr)
[0, 1, 2, 3]
nums = [1, 2, 3, 4]
fruit = ["Apples", "Peaches", "Pears", "Bananas"]
print([(i, f) for i in nums for f in fruit])
[(1, 'Apples'), (1, 'Peaches'), (1, 'Pears'), (1, 'Bananas'),
(2, 'Apples'), (2, 'Peaches'), (2, 'Pears'), (2, 'Bananas'),
(3, 'Apples'), (3, 'Peaches'), (3, 'Pears'), (3, 'Bananas'),
(4, 'Apples'), (4, 'Peaches'), (4, 'Pears'), (4, 'Bananas')]
BDFL Pronouncements
The syntax proposed above is the Right One.
The form [x, y for ...]
is disallowed; ❌
one is required to write [(x, y) for ...]
✅
The form [... for x... for y...]
nests, with the last index varying fastest, just like nested for loops. 🚀
https://peps.python.org/pep-0202/
List displays
list_display ::= "[" [starred_list | comprehension] "]"
https://docs.python.org/3/reference/expressions.html#list-displays
REPL
https://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3
demos
list, enumerate, range, lambda, for...loop
#!/usr/bin/env python3
# coding: utf8
__author__ = 'xgqfrms'
__editor__ = 'vscode'
__version__ = '1.0.1'
__github__ = 'https://github.com/xgqfrms/Raspberry-Pi'
__git__ = 'https://github.com/xgqfrms/Raspberry-Pi.git'
__copyright__ = """
Copyright (c) 2012-2050, xgqfrms; mailto:xgqfrms@xgqfrms.xyz
"""
"""
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-01-01
* @updated 2023-07-01
*
* @description
* @augments
* @example
* @link
*
*/
"""
# ✅ List types
from typing import List
# class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# result = []
# print("len(result)", len(result))
# # print("len(result)", len(result), result[0])
# # for i, item in enumerate(nums):
# # temp = item
# # # ❌ IndexError: list index out of range
# # print("len(result)", len(result), result, i)
# # if(len(result) > 0):
# # print("✅", result[i])
# # temp += result[i]
# # # result[i] = temp
# # result.append(temp)
# return result
# 🚀
# class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# for i, item in enumerate(nums):
# if(i > 0):
# nums[i] += nums[i - 1]
# return nums
# 🚀
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
for i in range(1,len(nums)):
nums[i] += nums[i - 1]
return nums
# ✅
# class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# for i in range(len(nums)):
# if(i > 0):
# nums[i] += nums[i - 1]
# return nums
# ✅
# class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# temp = 0
# result = []
# for item in nums:
# temp += item
# result.append(temp)
# return result
# ✅
# class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# result = []
# for i, item in enumerate(nums):
# result.append(item)
# for j in range(len(result) - 1):
# result[i] += nums[j]
# return result
# test cases
t1 = [1,2,3,4]
t2 = [1,1,1,1,1]
t3 = [3,1,2,10,1]
tests = [t1, t2, t3]
r1 = [1,3,6,10]
r2= [1,2,3,4,5]
r3 = [3,4,6,16,17]
results = [r1, r2, r3]
def test():
solution = Solution()
for index, test in enumerate(tests):
value = solution.runningSum(test)
result = results[index]
if(str(value) == str(result)):
print("✅ passed", index)
else:
print("❌ failed", value, result)
if __name__ == '__main__':
print('main / init 👻')
try:
test()
except KeyboardInterrupt:
print('Ctrl + C exit ✅')
except RuntimeError as error:
print('error =', error, error.args[0])
pass
except Exception as error:
print('exception =', error)
raise error
finally:
# cleanup
print('finally, clear buffer! 👻')
# print('exit Python REPL')
exit()
'''
# $ python3 ./1480_running-sum-of-1d-array.py
$ py3 ./1480_running-sum-of-1d-array.py
main / init 👻
✅ passed 0
✅ passed 1
✅ passed 2
finally, clear buffer! 👻
https://leetcode.com/problems/running-sum-of-1d-array/description/
'''
# 🚀
# class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# for i, item in enumerate(nums):
# if(i > 0):
# nums[i] += nums[i - 1]
# return nums
# 🚀
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
for i in range(1,len(nums)):
nums[i] += nums[i - 1]
return nums
# ✅
# class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# for i in range(len(nums)):
# if(i > 0):
# nums[i] += nums[i - 1]
# return nums
# ✅
# class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# temp = 0
# result = []
# for item in nums:
# temp += item
# result.append(temp)
# return result
# ✅
# class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# result = []
# for i, item in enumerate(nums):
# result.append(item)
# for j in range(len(result) - 1):
# result[i] += nums[j]
# return result
https://leetcode.com/problems/running-sum-of-1d-array/submissions/
#!/usr/bin/python3
nums = [1,2,3,4,5]
arr = [x for x in nums[1:]]
print("arr =", arr)
for j in nums[1:]:
print("j =", j)
"""
$ py3 ./list-for-loop.py
arr = [2, 3, 4, 5]
j = 2
j = 3
j = 4
j = 5
"""
python dynamic create list
python create list with for loop one line
https://stackoverflow.com/questions/1545050/python-one-line-for-expression
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17600173.html
未经授权禁止转载,违者必究!