我想知道如何使用list comprehension替换列表的值。例如
theList = [[1,2,3],[4,5,6],[7,8,9]]
newList = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(theList)):
for j in range(len(theList)):
if theList[i][j] % 2 == 0:
newList[i][j] = 'hey'
我想知道如何将其转换为列表理解格式。
答案 0 :(得分:4)
你可以做一个嵌套列表理解:
[[1, 'hey', 3], ['hey', 5, 'hey'], [7, 'hey', 9]]
返回
<style type="text/css">
img.svg { fill: #b9c9d4; }
</style>
<head>
<title></title>
</head>
<body>
<img class="svg" src="logo.svg" alt="" >
</body>
</html>
答案 1 :(得分:1)
theList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
newList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for i in range(len(theList)):
for j in range(len(theList)):
if theList[i][j] % 2 == 0:
newList[i][j] = "hey'ere"
new_list2 = [["hey'ere" if x %2 == 0 else x for x in row]
for row in theList]
assert newList == new_list2
newList
或者,如果您根据theList
中的值替换newList = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
newList[:] = [["hey" if x % 2 == 0 else y for x, y in zip(row1, row2)]
for row1, row2 in zip(theList, newList)]
print(newList)
中的项目,则可以执行以下操作:
[[10, 'hey', 30], ['hey', 50, 'hey'], [70, 'hey', 90]]
Function UsedRange(r As Range, Optional FromRowOne As Boolean = True) As Range
Dim rTop As Range
Dim rEnd As Range
With r.Worksheet
Set rTop = r.EntireColumn.Cells(1, 1)
If Not FromRowOne Then
If IsEmpty(rTop) Then
Set rTop = rTop.End(xlDown)
End If
End If
Set rEnd = r.EntireColumn.Cells(.Rows.Count, 1)
If IsEmpty(rEnd) Then
Set rEnd = rEnd.End(xlUp)
End If
If rTop.Row < rEnd.Row Then
Set UsedRange = .Range(rTop, rEnd)
End If
End With
End Function
答案 2 :(得分:0)
def f(a, b):
print(a, b)
return 'hey' if a % 2 == 0 else b
newList = [[f(a, b) for a, b in zip(r1, r2)] for r1, r2 in zip(theList, newList)]