li_test1 = [1, 11, 3, 14, 5]
li_test2 = [12, 2, 13, 4, 15]
li_test3 = []
for i in range(len(li_test1)):
if li_test1[i] > li_test2[i]:
li_test3.append(li_test1[i])
elif li_test3[i-1] > li_test1[i] :
li_test3.append(li_test2[i])
Can I use it right away while making the li_test3 list?
elif li_test3[i-1] > li_test1[i] :
Is there any way I can use it?
python
It is not recommended, but it is not impossible.
The problem with the code you created is that when comparing the values of the two lists, the value in the second list is less than or equal to the value in the first list, the index is used to refer to the new list unconditionally.
At first, the list is empty, but if you try to load the value using the index, you might experience problems.
In some cases, you do not add values to the new list, but when you refer to the values in the new list, you may also have problems trying to reuse the index that you used in the previous for statement.
The length of the list is 2, but if you try to index a value of 3 or higher, the list index out of range
error occurs as if you were indexing an empty list.
Add code for when the list is initially empty to prevent this error.
Also, to check the last value added to the new list, it is sufficient to use [-1]
instead of [i-1]
.
It can be implemented in the following way, but I don't know where and how to use it.
As previously written answers, li_test3 has fewer elements than the other two lists, so it cannot be considered a working limit.
Also, there should be one standard, but I don't know why we compare random numbers according to location.
li_test1 = [1, 11, 3, 14, 5]
li_test2 = [12, 2, 13, 4, 15]
li_test3 = []
for a, b in zip(li_test1, li_test2):
if a>b:
li_test3.append(a)
"""
a b
1 12
11 2
3 13
14 4
5 15
"""
print(li_test3)
# [11, 14]
for a, b, c in zip(li_test1, li_test2, li_test3):
if c-1 > a:
li_test3.append(b)
print(li_test3)
# [11, 14, 12, 2, 13, 15]
© 2024 OneMinuteCode. All rights reserved.