split a string in list - python-3.x

I have a list containing string values:
a_list = ['1/one','2/two','3/three']
I want to split the number from a word like this:
number = [1,2,3]
words = [one,two,three]
Then I make a condition if the number equal one or three then add the numbers to a new list. here is my code:
import re
new_list = []
for i in a_list:
word =re.findall(r"[\w']+",i)[1]
number = re.findall(r"[\w']+",i)[0]
if word == 'one' or word == 'three' :
new_list.append(number)
I got an error :
IndexError: list index out of range
any help?... Thanks in advance

Related

Suppose we have a list of 3-letter words with 3 elements, but each word is also a list. The function return the character at the given index

Suppose we have a list of 3-letter words with 3 elements, but each word is also a list. See example below:
word_list = [ ['r','e','d'] , ['p','e','a'] , ['z','i','p'] ]
Create a function named getCharacterAt that accepts 2 arguments - word_list and index_of_character. The function should be able to return the character at the given index. (If index_of_character is 3, we get 3rd letter in the whole list which is 'd'. If it is 5, we get 'e'. If 9, we get 'p'.
word_list = [ ['r','e','d'] , ['p','e','a'] , ['z','i','p'] ]
new_word_list = []
for i in word_list:
new_word_list = new_word_list + i
def getCharacterAt(word_list: list, index_of_character: int):
return word_list[index_of_character - 1]
print(getCharacterAt(new_word_list, 3))
# Output: d
In this case, I have created a 'new_word_list' with the union of each element of 'word_list'. Then, following your description, you just return the index - 1 element of the request (remember that first list index is 0)

List Comprehension with "if" is not returning the same output as when I make a For Loop when counting the number of unique letters in a word

Can someone explain to me why there is a difference in output when using nested loops vs nested list comprehension?
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def unique_english_letters (word) :
unique = []
for i in word:
if i not in unique:
unique.append(i)
return len(unique)
print(unique_english_letters("mississippi"))
# outputs 4 (my expected output)
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def unique_english_letters (word) :
unique = []
unique = [i for i in word if i not in unique]
return len(unique)
print(unique_english_letters("mississippi"))
#outputs 11 (length of mississippi"
^ Output
In the second example, this:
unique = []
unique = [i for i in word if i not in unique]
is equivalent to:
unique = [i for i in word if i not in []]
unique is an empty list while the list comprehension is evaluated, and then unique is re-assigned the results.
To do what you want in simple terms, use a set which can only contain unique values, and use set intersection(& operator) to generate the set of letters contained in word:
letters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
def unique_english_letters(word):
return len(letters & set(word))
print(unique_english_letters("mississippi"))
# output: 4

How to compare an input() with a variable(list)

(Im using python on Jupiter Notebook 5.7.8)
I have a project in which are 3 lists, and a list(list_of_lists) that refer to those 3.
I want my program to receive an input, compare this input to the content of my "list_of_lists" and if find a match I want to store the match in another variable for later use.
Im just learning, so here is the code I wrote:
first = ["item1", "item2","item3"]
second = ["item4","item5","item6"]
list1 = [first,second]
list2 = ["asd","asd","asd"]
list_of_lists = [list1,list2]
x = input("Which list are you going to use?: ")
for item in list_of_lists:
if item == x:
match = item
print(match)
print('There was a match')
else:
print('didnt match')
I expect a match but it always output "the didnt match",
I assume it fail to compare the contect of the input with the list inside the list_of lists. The question is also why and how to do it properly(if possible), thanks.
input in python3 returns a string. if you want to convert it into a list, use ast.literal_eval or json.loads or your own parsing method.
list_str = input("Which list are you going to use?: ")
user_list = ast.literal_eval(list_str)
assert isinstance(user_list, list)
...
# do your thing...
So here i tried this code, and it does what i desire, I dont know if its too rudimentary and if there is another way to achieve this.
Here I use a second list to catch the moment when there is a match, after I give to that list the value of my true list and from there print it to be used.
I was wondering if there is a way to take out of the ressults the symbols "[]" and the quotes '', so I can have a clean text format, thanks for the help
first = ["item1", "item2","item3"]
second = ["item4","item5","item6"]
list1 = [first,second]
list2 = ["asd","asd","asd"]
list3 = ["qwe","qwe","qwe"]
list_of_lists = [list1,list2,list3]
reference_list = ["list1","list2","list3"]
count = -1
x = input('Which list are you going to use? ')
for item in reference_list:
count += 1
if x == item:
reference_list = list_of_lists
print(reference_list[count])

Recreate the code without list comprehension

I am learning about list comprehension therefore i would like to recreate the code without list comprehension.
The code is the following:
items=[x for x in input().split(",")]
items.sort()
print (items)
This is how i recreated it:
print ("Enter comma seperated words: ")
userinput = input ().split(",")
words = []
for i in range (len(userinput)):
words.append(userinput)
words.sort()
print (words)
I expect the output should be in alphabetical order but it does not.
Let's say our input is this...
userinput = 'foo,bar'
Using the list comprehension code...
items=[x for x in userinput.split(",")]
items.sort()
print (items)
Output becomes: `['bar', 'foo']`
However, if we use your recreated code..
userinput = userinput.split(',')
words = []
for i in range (len(userinput)):
words.append(userinput)
words.sort()
print (words)
Output becomes: `[['foo', 'bar']]
Why is this?
When the line userinput = userinput.split(',') is run, userinput now becomes ['foo', 'bar'].
Therefore, when words.append(userinput) is run, what it is actually doing is saying words.append(['foo', 'bar']), and thus you are appending a list into a list meaning that words = [['foo', 'bar']].
words.sort() will not sort nested lists within itself, therefore, your list isnt sorted.
Therefore the fix is to append each element of userinput into words instead of appending userinput as a list into words.
userinput = userinput.split(',')
words = []
for i in range (len(userinput)):
words.append(userinput[i])
words.sort()
print (words)
Output becomes: ['bar', 'foo']

Return a dictionary with keys that are the first letter of a word and lists of those words?

I want to write a function that takes a list of words and keys and outputs those keys as dictionary keys with any words starting with that letter attached.
How could this be achieved using simple python 3 code?
eg. takes (['apples', 'apple', 'bananna', 'fan'], 'fad')
returns {'a' : ['apple', 'apples'], 'f' : ['fan']}
so far i have tried:
def dictionary(words, char_keys)
char_keys = remove_duplicates(char_keys)
ret = {}
keys_in_dict = []
words = sorted(words)
for word in words:
if word[0] in char_keys and word[0] not in keys_in_dict:
ret[word[0]] = word
keys_in_dict.append(word[0])
elif word[0] in keys_in_dict:
ret[word[0]] += (word)
return ret
This gives kinda the right output but it the output is in a single string rather than a list of strings.(the def is not indented properly i know)
If the input is a list of strings, you can check if the char is in the dict, if yes, append the word, otherwise add a list with the word:
def dictionary(inpt):
result = {}
for word in inpt:
char = word[0]
if char in result:
result[char].append(word)
else:
result[char] = [word]
return result
The modern way to do this is to use a collections.defaultdict with list as argument.
def dictionary(inpt):
result = defaultdict(list)
for word in inpt:
result[word[0]].append(word)
return result
Not sure if your list of inputs are consisted with only strings or it can also include sub-lists of strings (and I'm not so sure why "fad" disappeared in your example). Obviously, in the latter scenario it will need some more effort. For simplicity I assume if contains only strings and here's a piece of code which hopefully points the direction:
d = {}
for elem in input_list[0]:
if elem[0] in input_list[1]
lst = d.get(elem[0], [])
lst.append(elem)
d[elem] = lst

Resources