This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 5 years ago.
I'm currently doing one of the code fight's challenges, basically the challenge is to find the number of common characters between two strings. I came up with the solution below. I already passed the challenge, but I cannot figure out why I would have to iterate over the list twice and also not in every case. Thanks in advance for any explanations.
strings = [
["aabcc", "adcaa"],
["abca", "xyzbac"],
["assssbs", "aasaaaa"],
["zzzzzz", "zzz"],
["abcdefghxyzttw", "hgfedcbaabcwwt"] #<-- the strings failing with one iteration
]
def commonCharacterCount(s1, s2):
s1, s2 = sorted(list(s1)), sorted(list(s2))
matches = []
def matched(i):
matches.append(i)
s1.remove(i)
s2.remove(i)
[matched(i) for i in s1 if i in s2]
[matched(i) for i in s2 if i in s1]
[matched(i) for i in s1 if i in s2] #<-- Second for loop to find f
return len(matches)
def test():
for i in strings:
commonCharacterCount(i[0], i[1])
return
test()
You simply try this
lis=["abcdef","abcdv"]
match=[i for i in lis[0]if i in lis[1]]
It gives out put
['a', 'b', 'c', 'd']
Edit
For only one time check
>>> a
['abcc', 'abbbc']
>>> check0=list(a[0])
>>> check1=list(a[1])
>>> match=list()
>>> for i in check0:
if i in check1:
check1.remove(i)
match.append(i)
Out Put
['a', 'b', 'c']
Related
This question already has answers here:
How to remove 2nd occurrence of an item in a list using remove() without removing 1st occurrence in Python
(6 answers)
Closed 3 years ago.
here I have a list, it contains many duplicate elements I want to remove the second repeated element in list how can I remove the particular element in the list?
l=["a","b","a","a","a"]
here i want to remove "a" after the second element of b(i.e a[3])
without using the index how can I remove the element in the list.
you can search the list for the index of b and then use that as the start point for searching for a's index
l=["a","b","a","a","a"]
b_index = l.index("b")
print("b index is", b_index)
first_a_after_b = l.index("a", b_index)
print("first a after b is at index", first_a_after_b)
del l[first_a_after_b]
print(l)
OUTPUT
b index is 1
first a after b is at index 2
['a', 'b', 'a', 'a']
Python list.index takes start argument which we can use to look for a's after first occurrence of b.
l = ["a","b","a","a","a"]
l.pop(l.index('a', l.index('b')+1))
# l = ['a', 'b', 'a', 'a']
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
I have the following code:
myList = ['A','B','C']
for letter in myList:
letter = myList
When running it I would expect variables to be assigned as following:
A = ['A', 'B', 'C']
B = ['A', 'B', 'C']
C = ['A', 'B', 'C']
Instead it seems that the loop is only assigning values to the "myList" component of the loop and forgetting to assign the anything for "letter". Hence the actual variable assignment looks like this:
letter = ['A', 'B', 'C']
Can someone please explain to me why python does not replace "letter" with values from "myList"?
Thank you!
It DOES replace "letter" with values from "myList": it put the value in the variable letter.
What it doesn't do is assign those values to a variable whose name is contained in letter, because that's not how assignment works
This question already has answers here:
How to convert list to string [duplicate]
(3 answers)
Closed 3 years ago.
I have this list:
x = ['nm0000131', 'nm0000432', 'nm0000163']
And I would like to convert it to:
'nm0000131',
'nm0000432',
'nm0000163'
e.g: I would like convert a list of strings (x) to 3 independent strings.
If you want three separate string you can use for loop.
Try the following code:
x = ['nm0000131', 'nm0000432', 'nm0000163']
for value in x:
print(value)
Output will be like:
nm0000131
nm0000432
nm0000163
The following code will display an output like "nm0000131" ,"nm0000432" ,"nm0000163":
x = ['nm0000131', 'nm0000432', 'nm0000163']
str1 = '" ,"'.join(x)
x = '"'+str1+'"'
print(x)
As you mentioned in the comment I would like to include some more points to my answer.
If you want to get the key-value pairs then try the following code.
y = {'131': 'a', '432': 'b', '163': 'c'}
w = []
for key, value in y.items():
w.append(value)
print(w)
Output:
['c', 'a', 'b']
This question already has answers here:
Why can't I call read() twice on an open file?
(7 answers)
Closed 4 years ago.
Why below two statements are not returning same lists?
with open("test.py") as f:
upChars = list(filter(lambda ch : ch.isupper(), [ch for ch in f.read()]))
upChars1 = [ch1 for ch1 in f.read() if ch1.isupper()]
print(f"\n1: {upChars},\n2: {upChars1}")
Output :
1: ['T', 'B', 'S', 'T', 'T', 'C', 'T', ...contains all uppercase chars],
2: []
That's because you cannot read a file twice. After the first read(), the descriptor is at the end of file. Usually, when preforming multiple things on a file, putting it into a list makes sense:
test = f.read()
then you can use it multiple times. Try and print the result of a double read to see this in action. If you really insist, you could f.seek(0) to reset it, but this is more overhead than its worth.
This question already has answers here:
Finding the index of an item in a list
(43 answers)
Closed 6 years ago.
We can access the value of a certain index in a list like so:
letters = ['a','b','c','d','e','f']
print letters[1]
The code above will print the letter 'b', because it is in the index 1 of the list, letter. So in this way, we can access a certain object in a list.
Now, if we assume that letters = ['a','b','c','d','e','f'], what code should we type to access the index of a certain object (assume it is the letter, 'c') in the list, letters?
Any and all help will be appreciated.
If letters = ['a', 'b', 'c', 'd', 'e', 'f'], the following will return the index of c in letters:
>>> letters.index('c')
2
If the value is not in the list, it will raise an error instead:
>>> letters.index('k')
valueError: 'k' is not in list