LisaSwiss
LisaSwiss

Reputation: 51

Compare two lists and find the unique values

I had just started with Python and have no real programming experience except SQL.

My task:

  1. Find words that exists on both even and odd lines.
  2. Words that only exists on even lines
  3. Words that only exists on odd lines

All punctuations and uppercase are removed so we dont need to worry about that. However, it is several words on the same line

The output should look something like this

Common words on both lines: ['I', 'the', 'am', 'all', 'as', ...] 
Only even lines : ['yellow', 'christmas', 'smell', ...] 
Only odd lines: ['yours', 'war', 'may', 'remote', ...]

I started like

evens, odds = set(), set()
with open('textfile.txt') as f:
    for index, row in enumerate(f):
        if index % 2 == 0:
            evens.update(row.split())
        else:
            odds.update(row.split())
commons = sorted(evens & odds)

How should I continue from here? My main problem is to print out the unique words for evens and odds. A minor problem is to transpose my list in commons to a row.

Upvotes: 4

Views: 326

Answers (3)

MKM2
MKM2

Reputation: 31

Firstly, to know the common word in even and odd lines, you need to get two lists of the words of even and odd lines.This is how to make two lists of these.

enter image description here

Then you have to find the common words exists in two lists.If the word is a common word of two lists, delete this word from two lists and add it to the new list of common words.

enter image description here

Upvotes: 0

Rohit Mishra
Rohit Mishra

Reputation: 571

List comprehension is an important concept to learn, if you want to use python regularly.

So you can try for problem statement 1:

combine=['I', 'the', 'am', 'all', 'as','yellow'] 
even_line=['yellow', 'christmas', 'smell']
odd_line=['yours', 'war', 'may', 'remote','yellow']

words_in_both_odd_even=[i for i in combine for j in even_line for k in odd_line if (i==j and i==k)]

words_in_both_odd_even

For problem statement 2:

words_in_even_line=[i for i in combine for j in even_line if (i==j)]
words_in_even_line

For problem statement 3:

words_in_odd_line=[i for i in combine for k in odd_line if (i==k)]

words_in_odd_line

If you are looking for unique values in any of the above there problem statement output- Then you can use set(words_in_both_odd_even) or set(words_in_even_line) or set(words_in_odd_line)

Upvotes: 0

Daniel
Daniel

Reputation: 42748

Use the difference operator -:

only_odd = odd - even

Upvotes: 3

Related Questions