[英]how do I compare subsequently integers in two lists?
我有兩個列表 nums1 = [1,5,10,44,4] 和 nums2 = [5,3,10,55,3]; 如果我想比較兩個列表的第一個數字,然后是第二個數字,然后是第三個數字,依此類推……即 1 與 5、5 與 3、10 與 10 等。
我怎樣才能做到這一點?
我最初的想法是使用兩個 for 循環,但后來我將所有列表與每個 integer 進行比較,而我所追求的只是將一個列表中的一個 integer 與另一個列表中的另一個 Z157DB7DF530023575515ZD36E8Z 進行比較。
使用 zip:
for a, b in zip(nums1, nums2):
# zip loops through both lists in parallel
compare = "less" if a < b else "equal" if a == b else "greater" # Example compare
print(f"{a} {compare} {b}")
Output
1 less 5
5 greater 3
10 equal 10
44 less 55
4 greater 3
假設兩個列表的長度相等,您可以使用 while 循環
i = 0
while i < len(nums1):
if num1[i] == nums2[i]:
# do something when equal
i = i + 1
做就是了:
nums1 = [1,5,10,44,4]
nums2 = [5,3,10,55,3]
nums_res = [max(l1, l2) for l1, l2 in zip(nums1,nums2)]
nums1 = [1,5,10,44,4]
nums2 = [5,3,10,55,3]
result = [nums1[x] > nums2[x] for x in range(len(nums1))]
我假設兩個列表的長度相同。
結果: nums1中的元素 > nums2 中的元素
[False, True, False, False, True]
x, y = [1,5,10,44,4], [5,3,10,55,3]
# If both list have same length
for i in range(len(x)):
# Compare here with the index
if x[i] == y[i]:
# Do something
print(x[i], "is same in both lists")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.