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']
Related
This question already has answers here:
Numpy 'where' on string
(4 answers)
Closed 4 years ago.
word2 = "find"
np.where(dictionary == word2)[0]
The dictionary variable is a numpy array with thousands of words in the english dictionary, when looking for the index of a word, numpy also returns the index of all the strings containing word2 as a substring.
Does anyone has an idea of how to fix this? I would like to return just the perfect string match
Thanks
a = np.array(['apple', 'orange', 'apple', 'banana'])
arr_index = np.where(a == 'apple')
print arr_index
print a[arr_index]
Refer this post
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']
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
i have the task to get the String 'AAAABBBCCDAABBB' into a list like this: ['A','B','C','D','A','B']
I am working on this for 2 hours now, and i can't get the solution. This is my code so far:
list = []
string = 'AAAABBBCCDAABBB'
i = 1
for i in string:
list.append(i)
print(list)
for element in list:
if list[element] == list[element-1]:
list.remove(list[element])
print(list)
I am a newbie to programming, and the error "TypeError: list indices must be integers or slices, not str" always shows up...
I already changed the comparison
if list[element] == list[element-1]
to
if list[element] is list[element-1]
But the error stays the same. I already googled a few times, but there were always lists which didn't need the string-format, but i need it (am i right?).
Thank you for helping!
NoAbL
First of all don't name your variables after built in python statements or data structures like list, tuple or even the name of a module you import, this also applies to files. for example naming your file socket.py and importing the socket module is definitely going to lead to an error (I'll leave you to try that out by yourself)
in your code element is a string, indexes of an iterable must be numbers not strings, so you can tell python
give me the item at position 2.
but right now you're trying to say give me the item at position A and that's not even valid in English, talk-less of a programming language.
you should use the enumerate function if you want to get indexes of an iterable as you loop through it or you could just do
for i in range(len(list))
and loop through the range of the length of the list, you don't really need the elements anyway.
Here is a simpler approach to what you want to do
s = string = 'AAAABBBCCDAABBB'
ls = []
for i in s:
if ls:
if i != ls[-1]:
ls.append(i)
else:
ls.append(i)
print(ls)
It is a different approach, but your problem can be solved using itertools.groupby as follows:
from itertools import groupby
string = 'AAAABBBCCDAABBB'
answer = [group[0] for group in groupby(string)]
print(answer)
Output
['A', 'B', 'C', 'D', 'A', 'B']
According to the documentation, groupby:
Make an iterator that returns consecutive keys and groups from the iterable
In my example we use a list comprehension to iterate over the consecutive keys and groups, and use the index 0 to extract just the key.
You can try the following code:
list = []
string = 'AAAABBBCCDAABBB'
# remove the duplicate character before append to list
prev = ''
for char in string:
if char == prev:
pass
else:
list.append(char)
prev = char
print(list)
Output:
['A', 'B', 'C', 'D', 'A', 'B']
In your loop, element is the string. You want to have the index.
Try for i, element in enumerate(list).
EDIT: i will now be the index of the element you're currently iterating through.
This question already has answers here:
Generate a matrix containing all combinations of elements taken from n vectors
(4 answers)
Closed 7 years ago.
I have the letters "A", "B", "C", "D", and "E" and I want to generate all possible strings of length 7 with these letters (redundancy allowed). So, I would like to get:
AAAAAAA
AAAAAAB
AAAAAAC
AAAAAAD
AAAAAAE
...
So on and so forth with all possible strings. I know how to do this manually via the following, create:
A = ['A'], B = ['B'], etc...then create embedded for loops to concatenate all elements. However, I would like to just feed in a generic list of ABCDE in a function, and just feed the function an integer to get a variable result. How could I do this?
Something like this?
Test = 'ABCDE';
A = cell(7, 1); %//pre-allocating for speed
[A{:}] = ndgrid(Test);
y = cellfun(#(Test) {Test(:)} , A);
y = horzcat (y{:});
>>
AAAAAAA
BAAAAAA
CAAAAAA
DAAAAAA
EDIT: ops... didn't see the 7..