multiple list compare with file line in python - python

Code (incomplete):
list1 = ['1', '2', '3']
list2 = ['a', 'b', 'c']
list3 = ['12' '13' '14']
for list_in in list1:
with open("buffer_file") as f:
for line in f:
if len(line.split(" ")) >= 3:
var1 = line.split(" ")
if var1[0] == list1[0] and var[1] == list2[0] and var[3] == list3[0]:
buffer_file:
no
priority enabled
1 a 12
2 b 13
3 d 14
pump it
What I am trying here is if in file line and list values are matched then print file line is matched.
Example 1:
list1[0], list2[0], list3[0]
is matched with line contains 1 a 12 values so print matched
Example 2:
list1[1], list2[1], list3[1]
is matched with line contains 2 b 13 values so print matched
Example 3:
list1[2], list2[2], list3[2]
is not matched because line contains 3 d 12 values print not matched and also print not matched element that is d
Any one please suggest me what is the best way get this done. I am struck in middle of my code.

You can zip your three lists so that you can grab and check their values as triplets of aligned elements.
expected = zip(list1, list2, list3)
print expected
[ ('1', 'a', '12'), ('2', 'b', '13'), ... ]
If the lines in the file match your list elements one to one, you can then use zip() again to loop through the expected and actual values together. zip() is your friend. (If the file has extra lines, use a variable to walk down the list of triples.)
with open("buffer_file") as f:
for exp, actual in zip(expected, f):
if exp == actual.split(): # compares two 3-tuples
<etc.>

Reading between the lines a bit here. Essentially sounds line you want to ignore all the lines are't triples, enumerate over the file and find matches in your original list.
values = [
['1', '2', '3'],
['a', 'b', 'c'],
['12', '13', '14'],
]
def triples(line):
return len(line.split()) >= 3
with open("test_file.txt") as f:
content = filter(triples, (map(str.strip, f.readlines())))
# Loop over the file keeping track of index
for index, line in enumerate(content):
# Compare split line and triples
if line.split() == list(map(itemgetter(index), values)):
print(line)
Gives me, where "test_file.txt" contains your listed input
1 a 12
2 b 13

Related

How to compare two lists and remove elements in python

I have two lists. I am trying to remove all the elements in the first list occurred prior to any element in the second list. This should be happened only once.
As for an example:
Let,
list1 = ['a','d','k','1','3','a','f','3']
list2=['1','2','3','4','5']
what my resulting list should be:
listResult=['1','3','a','f','3']
in list 1, the element '1' is found in the list2. Hence, all the items prior to '1' has to be removed. This should not be happened with element '3', as the removing process has to be break after one removal.
I have tried with the following but it only considers one given specific element. what i am trying is to not only consider one element and to consider a list of elements.
from itertools import dropwhile
list1 = ['a','d','k','1','3','a','f','3']
element = '1'
list(dropwhile(lambda x: x != element, list1))
The in operator should be used in lambda for containment test:
>>> list(dropwhile(lambda x, s=frozenset(list2): x not in s, list1))
['1', '3', 'a', 'f', '3']
Another interesting but slightly inefficient solution:
>>> from itertools import compress, accumulate
>>> from operator import or_
>>> s = set(list2)
>>> list(compress(list1, accumulate((x in s for x in list1), or_)))
['1', '3', 'a', 'f', '3']
Because the default value of the second parameter of accumulate is equivalent to operator.add, and positive numbers are always regarded as true in Python, the or_ can be omitted:
>>> list(compress(list1, accumulate(x in s for x in list1)))
['1', '3', 'a', 'f', '3']
We can make a set using list1 which can be used to check if item in list2 present in list1.
If it is present, we can take the index of the item and take the subarray from the item index. Then we can break the loop.
list1 = ['a','d','k','1','3','a','f','3']
list2 = ['1','2','3','4','5']
listResult = []
set1 = set(list1)
for i in list2:
if (i in set1):
idx = list1.index(i)
listResult = list1[idx:]
break
print(listResult)

Code works only sometimes for removing odd or even index items

Question :​ Write a Python program to remove the characters which have odd or even index
values of a given string.
I tried to make a copy of the list by deep copy .
I ran a loop from first list and checked for even then used pop method on second list to remove that specific index from the second list .
This code works for some inputs , I think mostly for those which doesn't have any repeated characters and doesn't work for others.
Code
#!/usr/bin/python3
import copy
list1 = input("Enter a string ")
list1 = list(list1)
list2 = copy.deepcopy(list1)
for i in list1:
if list1.index(i)%2 != 0:
list2.pop(list2.index(i))
print(list2)
The outputs for some samples are :
123456789 -> ['1', '3', '5', '7', '9'], qwertyuiop -> ['q', 'e', 't', 'u', 'o'], saurav -> ['s', 'u'], 11112222333344445555 -> ['1', '1', '1', '1', '2', '2', '2', '2', '3', '3', '3', '3', '4', '4', '4', '4', '5', '5', '5', '5']
Read the documentation for index. It returns the index of the first occurrence of the given value. A simple print inside the loop will show you what's going on, in appropriate detail. This is a basic debugging skill you need to learn for programming in any language.
import copy
list1 = input("Enter a string ")
list1 = list(list1)
list2 = copy.deepcopy(list1)
for i in list1:
if list1.index(i)%2 != 0:
print(i, list1.index(i), list2.index(i))
list2.pop(list2.index(i))
print(list2)
print(list2)
output:
Enter a string google
o 1 1
['g', 'o', 'g', 'l', 'e']
o 1 1
['g', 'g', 'l', 'e']
e 5 3
['g', 'g', 'l']
['g', 'g', 'l']
... and that's your trouble. Fix your logic. You already know the needed index to save or remove. There is no need to extract the character, and then search for it again. You already know where it is.
Even better, simply slice the original string for the characters you want:
print(list1[::2])
Your problem is the list.index function. The documentation states that it "returns zero-based index in the list of the first item whose value is equal to x." Because you are calling it on list1 - and that is not modified - the result will always be list1.index('a') == 1 for example.
The correct solution would be to use enumerate. A further problem exists here - because you are indexing from an array that you have not modified, you indexes will be off after the first list.pop operation. Every item after the one removed will have been shifted by 1. To correct this, you could instead try building a list instead of emptying one:
#!/usr/bin/python3
list1 = input("Enter a string ")
list2 = []
for i, item in enumerate(list1):
if i % 2 == 0:
list2.append(item)
print(list2)
You don't need to iterate at all. Just reference the string elements directly.
st="123456789"
print('Odd: ', list(st[::2]))
print('Even: ', list(st[1::2]))
Output:
Odd: ['1', '3', '5', '7', '9']
Even: ['2', '4', '6', '8']
The method list.index(i) returns index in the list of the first item whose value is equal to i.
For example, "saurav".index('a') returns 1. when you call list2.pop(list2.index(i)) and you want to pop an a, it doesn't work well.
I think it can be simple using range as build-in function.
list1 = list(input("Enter a string "))
list2 = list()
for i in range(len(list1)):
if i % 2 == 0:
list2.append(list1[i])
print(list2)
It works with same way by following:
list1 = list(input("Enter a string "))
list2 = list()
for i in range(0, len(list1), 2):
list2.append(list1[i])
print(list2)
Also, you can use Extended Slices in Python 2.3 or above.
list1 = list(input("Enter a string "))
list2 = list1[::2]
print(list2)

write note of guitar using two lists

I have two lists:
list1=('a','b','c')
list2=('2','1','3')
and a text file
the text file has 3 lines so I want to add
'a' in the 2nd line
'-' in others,
'b' in the 1st line
'-' in others, and
'c' in the 3rd line
'-' in others according to the list1 and list2 like this
xxxx-b-
xxxxa--
xxxx--c
First task is to get the first list sorted correctly. This is easy if you zip the two lists together and then sort based on the (int-converted) line number:
>>> list1 = ['a', 'b', 'c']
>>> list2 = ['2', '1', '3']
>>> sorted(zip(list1, list2), key=lambda p: int(p[1]))
[('b', '1'), ('a', '2'), ('c', '3')]
Then you need to format the letter into the appropriate string. I'd do that with something like:
'xxxx' + ''.join(char if char == letter else '-' for char in 'abc')
so all together it's:
>>> for row in [
... 'xxxx' + ''.join(char if char == letter else '-' for char in 'abc')
... for letter, _line in sorted(zip(list1, list2), key=lambda p: int(p[1]))
... ]:
... print(row)
...
xxxx-b-
xxxxa--
xxxx--c
Now you just need to write it to the appropriate text file instead of printing it; since you don't specify how you want to do that (is it a specific text file? is it the parameter to a function? is it an existing file you're appending to?) I'll leave that part for you to fill in. :)
I did it but I think there is a good method than my
list1=['1','4','3','2']
list2=['a','b','c','d']
j=0
while j < len(list1):
with open("note2.txt",'r+') as f:
line = f.readlines()
note=""
f.seek(0)
for index,line in enumerate(line):
if index==list1[j]:
note+=line.strip()+ str(list2[j])+'\n'
else:
note+=line.strip()+ '-\n'
f.write(note)
f.close()
j+=1

creating two separate lists read from a file in python

Can i please know how the data from a file can be split into two separate lists. For example,
file contains data as 1,2,3,4;5,6,7
my code:
for num in open('filename','r'):
list1 = num.strip(';').split()
Here , i want a new list before semi colon (i.e) [1,2,3,4] and new list after semi colon (i.e) [5,6,7]
If you are certain that your file only contains 2 lists, you can use a list comprehension:
l1, l2 = [sub.split(',') for sub in data.split(';')]
# l1 = ['1', '2', '3', '4']
# l2 = ['5', '6', '7']
More generally,
lists = [sub.split(',') for sub in data.split(';')]
# lists[0] = ['1', '2', '3', '4']
# lists[1] = ['5', '6', '7']
If integers are needed, you can use a second list comprehension:
lists = [[int(item) for item in sub.split(',')] for sub in data.split(';')]
To get the final list you need to split on "," as well (and probably map() the result to int()):
with open("filename") as f:
for line in f:
list1, list2 = [x.split(",") for x in line.rstrip().split(";")]
Depending on the size of your file, you could simply read the whole file into a string at once and then first split by semicolon, then by comma:
with open('filename', 'r') as f: #open file
s = f.read() #read entire contents into string
lists = s.split(';') #split separate lists by semicolon delimiters
for l in lists: #for each list
l = [int(x) for x in l.split(',')] #separate the string by commas and convert to integers

how to match items between 2 different lists

I have 2 different lists:
['2', '1']
['equals', 'x']
I want to match the items so 2 = "equals" and 1 = "x" in order to recreate the original sentence "x equals x", also i have a third list which is:
['1', '2', '1']
I need the third list to recreate the original sentence since it has all the positions, to do this I thought of making the numbers equal to the words such as 1 = "x" and printing the list of numbers in order to have the full sentence. The problem is i do not know how to make the numbers equal to the words. Thanks for the help in advance
A dictionary might be what you need here which maps keys to values. You can create a dictionary from the first two lists by zipping them. And with this dictionary, it should be fairly straight forward to map any list of numbers to words:
mapping = dict(zip(['2', '1'], ['equals', 'x']))
mapping
# {'1': 'x', '2': 'equals'}
[mapping.get(num) for num in ['1', '2', '1']]
# ['x', 'equals', 'x']
To make the list a sentence, use join method:
" ".join(mapping.get(num) for num in ['1', '2', '1'])
# 'x equals x'

Categories

Resources