How to add elements of a string in a list without changing their types? - python-3.x

I have a string which includes str and int, for example string = "qA2". I want to add 'q', 'A' and 2 in a list but I don't want to change the type of elements. Is it possible?

You can use the .isdigit() method of the str class to do the following:
>>> s = "qA234"
>>> [int(x) if x.isdigit() else x for x in s]
['q', 'A', 2, 3, 4]
Note that this will fail for strings such as "x²" because ² (superscript 2) is considered a digit by the .isdigit() method for some reason. The following is safer:
>>> s = "3x²"
>>> [int(x) if "0" <= x <= "9" else x for x in s]
[3, 'x', '²']

Related

How to convert list of strings to integer indexes?

I have a list like this:
lst = [['ab', 'bc', 'cd'], ['dg', 'ab']]
I want to build a string indexer and convert it into:
lst_converted = [[1,2,3], [4,1]]
Do some processing on the converted list and then if the output is [[3], [2]]
lst_output = [['cd'], ['ab']]
Here,
'ab' = 1
'bc' = 2
'cd' = 3
'dg' = 4
Strings can be arbitrary and not necessarily characters. How to do this?
Use a list comprehension along with a dictionary to map the string literals to integer values:
d = {}
d['ab'] = 1
d['bc'] = 2
d['cd'] = 3
d['dg'] = 4
lst = [['ab', 'bc', 'cd'], ['dg', 'ab']]
lst_converted = [[d[y] for y in x] for x in lst]
print(lst_converted) # [[1, 2, 3], [4, 1]]

Make a list with non-decreasing order elements of a list in Python

I have a list a = [2,2,1,3,4,1] .
I want to make a new list c with the non-decreasing elements lists of list a.
That means my expected form is -
c = [[2,2],[1,3,4],[1]]
Here is my code:
>>> c = []
>>> for x in a:
... xx = a[0]
... if xx > x:
... b = a[:x]
... c.append(b)
... a = a[x:]
but my output is:
>>> c
[[2], [2]]
How can i make a list with all non-decreasing part of list a?
You can initialise the first entry of c with [a[0]] and then either append the current value from a to the end of the current list in c if it is >= the previous value, otherwise append a new list containing that value to c:
a = [2,2,1,3,4,1]
c = [[a[0]]]
last = a[0]
for x in a[1:]:
if x >= last:
c[-1].append(x)
else:
c.append([x])
last = x
print(c)
Output:
[[2, 2], [1, 3, 4], [1]]
If I understand what you are after correctly then what you want is to split the list every time the number decreases. If so then this should do what you need
c = []
previous_element = a[0]
sub_list = [previous_element]
for element in a[1:]:
if previous_element > element:
c.append(sub_list)
sub_list = []
previous_element = element
sub_list.append(previous_element)
c.append(sub_list)
Output:
In [1]: c
Out[2]: [[2, 2], [1, 3, 4], [1]]
There is possibly a clearer way to right the above, but it's pre coffee for me ;)
Also note that this code assumes that a will contain at least one item, if that is not always the case then you will need to either add an if statement around this, or re-structure the loop in a more while loop

Printing a list where values are in a specific distance from each other using Python

I have a list,
A = ['A','B','C','D','E','F','G','H']
if user input x = 4, then I need an output that shows every value that is 4 distance away from each other.
If starting from 'A' after printing values that are 4 distance away from each other ie: {'A', 'E'}, the code should iterate back and start from 'B' to print all values from there ie: {'B', 'F'}
No number can be in more than one group
Any help is going to be appreciated since I am very new to python.
this is what I have done
x = input("enter the number to divide with: ")
A = ['A','B','C','D','E','F','G','H']
print("Team A is divided by " +x+ " groups")
print("---------------------")
out = [A[i] for i in range(0, len(A), int(x))]
print(out)
My code is printing only the following when user input x =4
{'A', 'E'}
But I need it to look like the following
{'A', 'E'}
{'B', 'F'}
{'C', 'G'}
{'D', 'H'}
what am I doing wrong?
Use zip:
out = list(zip(A, A[x:]))
For example:
x = 4 # int(input("enter the number to divide with: "))
A = ['A','B','C','D','E','F','G','H']
print(f"Team A is divided by {x} groups")
print("---------------------")
out = list(zip(A, A[x:]))
print(out)
Outputs:
[('A', 'E'), ('B', 'F'), ('C', 'G'), ('D', 'H')]
Here you have the live example
If you want to keep the comprehension:
out = [(A[i], A[i+x]) for i in range(0, len(A)-x)]
**You can find my answer below.
def goutham(alist):
for passchar in range(0,len(alist)-4):
i = alist[passchar]
j = alist[passchar+4]
print("{"+i+","+j+"}")
j = 0
alist = ['a','b','c','d','e','f','g','h']
goutham(alist)

testing if the values of a dictionary are non zero with all() function

I use Python 3
I want to check if all of my tested values in the nested dictionary are non 0.
So here is the simplified example dict:
d = {'a': {'1990': 10, '1991': 0, '1992': 30},
'b': {'1990': 15, '1991': 40, '1992': 0}}
and I want to test if for both dicts 'a' and 'b' the values of the keys '1990' and '1991' are not zero
for i in d:
for k in range(2):
year = 1990
year = year + k
if all((d[i][str(year)]) != 0):
print(d[i])
so it should only return b, because a['1991']=0
but this is the first time I work with the all() function and I get the error core: TypeError: 'bool' object is not iterable
the error is in the if all() line
thank you very much!
This can done a bit more generally with a list comprehension where you iterate over the items in dict d. A simple comprehension to iterate over the keys and values in our dictionary looks like this:
>>> [k for k, v in d.items()]
['a', 'b']
In the above k will contain the keys and v the values. The comprehension also has an if clause. With that you can filter out the items you don't want. So we define years = ('1990', '1991'). Now we can do another comprehension to test our year values.
To iterate over only 'a', we could do this:
>>> [d['a'][y] for y in years]
[10, 0]
>>> all([d['a'][y] for y in years])
False
Gluing the whole thing together:
>>> d={'a' :{ '1990': 10, '1991':0, '1992':30},'b':{ '1990':15, '1991':40, '1992':0}}
>>> years = ('1990', '1991')
>>> [k for k, v in d.items() if all([v[y] for y in years])]
['b']
See the python docs for more information on list comprehensions.

How to insert a String as Integer to a List in Python

I need to insert a number (user input) as an integer to a Python list.
My code:
count = 0
list1 = []
for number in input():
if number != ' ':
list1.append(int(number))
Input: 10 11 12
Output: [1, 0, 1, 1, 1, 2]
Expected Output: [10, 11, 12]
Looping over a string (such as the one returned by input()) will loop over the individual characters in the string:
>>> s = 'hi guys'
>>> for char in s:
... print(char)
...
h
i
g
u
y
s
>>>
To loop over the "words" (i.e. substrings separated by spaces), you want to split() the user's input instead:
>>> s = 'hi guys'
>>> words = s.split()
>>> words
['hi', 'guys']
>>> for word in words:
... print(word)
...
hi
guys
>>>
So in your case, that would be:
for number in input().split():
list1.append(int(number))
We can leave the if number != ' ': out because split() already gets rid of all the spaces and simply returns a list of the numbers.
Here You Go
input_array = []
c_input = input('please enter the input\n')
for item in c_input.split():
input_array.append(int(item))
print (input_array)
input: - 1 11 23 23 456
Output:- [1, 11, 23, 23, 456]
i hope you find it useful
You should use split method to split the values as a list with string:
str_nums = input.split() #will give ['10','11','12']
then
lst_nums = []
for i in str_nums.split():
lst_nums.append(int(i))
print(lst_nums)
#output [10,11,12]
You can also use map and split together.
inp = "10 11 12"
print(list(map(int,inp.split(" "))))
#Output
[10,11,12]
Or
print([int(i) for i in input().split()])

Resources