Comparing 2 lists of strings, updating a 3rd list of strings in the same index position
Comparing 2 lists of strings, updating a 3rd list of strings in the same index position
If I have 3 lists of strings, for example:
['make ford', 'model taurus', 'color white']
['make chevy', 'model impala', 'color white']
['make ford', 'model taurus', 'color white']
What is the best way to detect changes that happened between list and 1 and 2; then update list 3?
For example, output would be:
['make chevy', 'model impala', 'color white']
The basic logic i'm trying to implement is:
if string1[0] = string2[0], then string3[0] remains unchanged
if string1[0] /= string2[0], then string3[0] is changed to string2[0]'s value
...and so on
Would it be better to convert these lists to arrays to do this?
l[3] = l[2]
I may have presented it confusingly. If the strings above were called A, B, C. I would like to iterate through A and B. If A[0] = B[0], then C[0] remains the same. If A[0] /= B[0], then C[0] is changed to B[0]'s string. Then move onto A[1],B[1],C[1], etc.
– yodish
Sep 18 '18 at 0:00
1 Answer
1
You can do something like this:
a = ['make ford', 'model taurus', 'color white']
b = ['make chevy', 'model impala', 'color white']
c = ['make ford', 'model taurus', 'color white']
for i in range(len(a)):
if a[i] != b[i]: c[i] = b[i]
print(c)
Output
['make chevy', 'model impala', 'color white']
This answer assumes all the list are of the same size. If the list are of different sizes you can compare (change) only the indices of the smallest list, in that case you can try something like this:
length = min(len(a), len(b), len(c))
for i in range(length):
if a[i] != b[i]:
c[i] = b[i]
print(c)
Thank you! I'm moving on to dealing with lists of different sizes, but this is exactly what I was looking for.
– yodish
Sep 18 '18 at 0:17
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
The way the problem is presented seems incorrect. Who would modify some of the elements? You want to implement some notifying system? Dumb answer (strictly to question, and related to examples): Periodically update the 3rd element:
l[3] = l[2]
– CristiFati
Sep 17 '18 at 23:46