在 python 中划分两个数字列表(使用列表理解而不使用 zip)
divide two list of numbers in python (using list comprehension and not using zip)
我对 python 语言还很陌生。我有两个这样的列表:
我还没有安装 numpy 包。
First_List = [10, 2, 5, 4, 100]
Second_List = [5, 10, 20, 20, 25]
如何将 First_List
中的每个元素除以 Second_List
中的元素?
输出应该是:
Result = [2, 0.2, 0.2, 4]
而且我想要输出中的列表,而不是数组!我怎样才能做到这一点 ?
我尝试使用这个:
>>> First_List = [10, 2, 5, 4, 100]
>>> Second_List = [5, 10, 20, 20, 25]
>>> First_List/Second_List
但我收到了这个错误:
Traceback (most recent call last): File "", line 1, in
First_List/Second_List TypeError: unsupported operand type(s) for /: 'list' and 'list'
假设First_List
和Second_List
有相同数量的元素,你可以迭代索引范围
任何一个列表的列表和从另一个列表的相应元素中划分元素:
First_List = [10, 2, 5, 4, 100]
Second_List = [5, 10, 20, 20, 25]
result = []
# get last index for the lists for iteration
end_index = len(First_List)
for i in range(end_index):
result.append(First_List[i]/Second_List[i])
result
输出:
[2.0, 0.2, 0.25, 0.2, 4.0]
这一切都可以使用列表理解来完成
result = [First_List[i]/ Second_List[i] for i in range(len(First_List))]
或者,可以使用 zip 和列表理解来完成(哪个更好)。
详情可以查看here:
result = [a/b for a,b in zip(First_List,Second_List)]
我对 python 语言还很陌生。我有两个这样的列表: 我还没有安装 numpy 包。
First_List = [10, 2, 5, 4, 100]
Second_List = [5, 10, 20, 20, 25]
如何将 First_List
中的每个元素除以 Second_List
中的元素?
输出应该是:
Result = [2, 0.2, 0.2, 4]
而且我想要输出中的列表,而不是数组!我怎样才能做到这一点 ? 我尝试使用这个:
>>> First_List = [10, 2, 5, 4, 100]
>>> Second_List = [5, 10, 20, 20, 25]
>>> First_List/Second_List
但我收到了这个错误:
Traceback (most recent call last): File "", line 1, in First_List/Second_List TypeError: unsupported operand type(s) for /: 'list' and 'list'
假设First_List
和Second_List
有相同数量的元素,你可以迭代索引范围
任何一个列表的列表和从另一个列表的相应元素中划分元素:
First_List = [10, 2, 5, 4, 100]
Second_List = [5, 10, 20, 20, 25]
result = []
# get last index for the lists for iteration
end_index = len(First_List)
for i in range(end_index):
result.append(First_List[i]/Second_List[i])
result
输出:
[2.0, 0.2, 0.25, 0.2, 4.0]
这一切都可以使用列表理解来完成
result = [First_List[i]/ Second_List[i] for i in range(len(First_List))]
或者,可以使用 zip 和列表理解来完成(哪个更好)。 详情可以查看here:
result = [a/b for a,b in zip(First_List,Second_List)]