How can i convert many variable to int in one line - python-3.x

I started to learn Python a few days ago.
I know that I can convert variables into int, such as x = int (x)
but when I have 5 variables, for example, is there a better way to convert these variables in one line? In my code, I have 2 variables, but what if I have 5 or more variables to convert, I think there is a way
You for help
(Sorry for my English)
x,y=input().split()
y=int(y)
x=int(x)
print(x+y)

You could use something like this .
a,b,c,d=[ int(i) for i in input().split()]

Check this small example.
>>> values = [int(x) for x in input().split()]
1 2 3 4 5
>>> values
[1, 2, 3, 4, 5]
>>> values[0]
1
>>> values[1]
2
>>> values[2]
3
>>> values[3]
4
>>> values[4]
5
You have to enter value separated with spaces. Then it convert to integer and save into list. As a beginner you won't understand what the List Comprehensions is. This is what documentation mention about it.
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
So the extracted version of [int(x) for x in input().split()] is similar to below function,
>>> values = []
>>> input_values = input().split()
1 2 3 4 5
>>> for val in input_values:
... values.append(int(val))
...
>>> values
[1, 2, 3, 4, 5]
You don't need to create multiple variables to save your values, as this example all the values are saved in values list. So you can access the first element by values[0] (0th element is the first value). When the number of input values are large, let's say 100, you have to create 100 variables to save it. But you can access 100th value by values[99].

This will work with any number of values:
# Split the input and convert each value to int
valuesAsInt = [int(x) for x in input().split()]
# Print the sum of those values
print(sum(valuesAsInt))
The first line is a list comprehension, which is a handy way to map each value in a list to another value. Here you're mapping each string x to int(x), leaving you with a list of integers.
In the second line, sum() sums the whole array, simple as that.

There is one easy way of converting multiple variables into integer in python:
right, left, top, bottom = int(right), int(left), int(top), int(bottom)

You could use the map function.
x, y = map(int, input().split())
print x + y
if the input was:
1 2
the output would be:
3
You could also use tuple unpacking:
x, y = input().split()
x, y = int(x), int(y)
I hope this helped you, have a nice day!

Related

How to subtract adjacent items in list with unknown length (python)?

Provided with a list of lists. Here's an example myList =[[70,83,90],[19,25,30]], return a list of lists which contains the difference between the elements. An example of the result would be[[13,7],[6,5]]. The absolute value of (70-83), (83-90), (19-25), and (25-30) is what is returned. I'm not sure how to iterate through the list to subtract adjacent elements without already knowing the length of the list. So far I have just separated the list of lists into two separate lists.
list_one = myList[0]
list_two = myList[1]
Please let me know what you would recommend, thank you!
A custom generator can return two adjacent items at a time from a sequence without knowing the length:
def two(sequence):
i = iter(sequence)
a = next(i)
for b in i:
yield a,b
a = b
original = [[70,83,90],[19,25,30]]
result = [[abs(a-b) for a,b in two(sequence)]
for sequence in original]
print(result)
[[13, 7], [6, 5]]
Well, for each list, you can simply get its number of elements like this:
res = []
for my_list in list_of_lists:
res.append([])
for i in range(len(my_list) - 1):
# Do some stuff
You can then add the results you want to res[-1].

Is there a python function to get all indexes from unique values?

I know there are methods like set() or np.unqiue() to get unique values from lists. But I search for a way to get the index for the value which occurs not more than one time.
example = [0,1,1,2,3,3,4]
what I looking for is
desired_index_list = [0,3,6]
Any suggestions?
Don't know of any prebuilt solution, probably you need to create your own. There are different approaches for that, but with classical Python implementation, you can easily create a count_dict and filter those values from the original list that have count of 1.
>>> from collections import Counter
>>> example = [0,1,1,2,3,3,4]
>>> counted = Counter(example)
>>> desired_index_list = [index for index, elem in enumerate(example) if counted[elem] == 1]
>>> desired_index_list
[0, 3, 6]
You can do this as a one-liner with a list comprehension:
from collections import Counter
[example.index(x) for x, y in Counter(example).items() if y == 1]
(Using Counter, return tuples for each item (x) and its number of occurrence (y), and return the index of the item if it's count is 1).

How can I append a different element for each list in a column in pandas?

I have a dataframe, df, with lists in a specific column, col_a. For example,
df = pd.DataFrame()
df['col_a'] = [[1,2,3], [3,4], [5,6,7]]
I want to use conditions on these lists and apply specific modifications, including appends. For example, imagine that if the length of the list is > 2, I want to append another element, which is the sum of the last two elements of the current list. So, considering the first list above, I have [1, 2, 3] and I want to have [1, 2, 3, 5].
What I tried to do was:
df.loc[:, col_a] = df[col_a].apply(
lambda value: value.append(value[-2]+value[-1])
if len(value) > 1 else value)
But the result in that column is None for all the elements of the column.
Can someone help me, please?
Thank you very much in advance.
The issue is that append is an in place function and returns None. You need to add two lists together. So a working example with dummy variable would be:
df = pd.DataFrame({'cola':[[1,2],[2,3,4]], 'dum':[1,2]})
df['cola']=df.cola.apply(lambda x: (x+[sum(x[-2:])] if len(x)>2 else x))
If you want to use append try this:
def my_logic_for_list(values):
if len(values) > 2:
return values + [values[-2]+values[-1]]
return values
df['new_a'] = df['a'].apply(my_logic_for_list)
You can not use append inside lambda function.

Sorting a list of strings items from an array [duplicate]

This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 3 years ago.
I'm new to python automation and wrote a script to get some port handles from Ixia and store into a list. I;m trynig to sort that port-handle where I see a problem.
I tried using the sort method but doesn;t work
>>> a
['1/1/11', '1/1/6']
>>> a.sort()
>>> a
['1/1/11', '1/1/6']
>>> d = a.sort()
>>> print(d)
None
>>>
Am i missing anything here .. kindly clarify
I want the output in the following format
1/1/6 1/1/11
Explanation
You are trying to sort a list of strings. Strings are naturally sorted in lexicographical_order, i.e. "10" < "11" < "2" < "5" < ..., so Python executes correctly what you want it to do. This being said, you need to transform your data into something that will be sorted as you want.
Solution
>>> a = ['1/1/11', '1/1/6']
>>> a
['1/1/11', '1/1/6']
>>> def to_tuple(string_representation):
... return tuple(int(i) for i in string_representation.split('/'))
...
>>> b = [to_tuple(element) for element in a]
>>> b.sort()
>>> b
[(1, 1, 6), (1, 1, 11)]
>>> a.sort(key=to_tuple)
>>> a
['1/1/6', '1/1/11']
Here we use the fact that tuple is sorted by default exactly how we want it to be sorted in your case (actually, it is also a lexicographical order, but now 11 is one element of a sequence and not two).
List b contains a transformed list, where each element is a tuple. And now sort will work as you want.
The second option, will be using a custom key operator. It is a function that returns a key to compare different elements of your list. In this case, key will be a corresponding tuple of integers and will be compared as you want.
Note 1
The second approach (with the key operator) will create an additional overhead during sorting as it will be called O(NlogN) times.
Note 2
You also tried using the result of sort function as a value, but it changes the given list in-place. If you want a sorted copy of your list, use sorted.

Print every two from a string with x

I will from a string with numbers and words ,than print it , separate every two Len with an x as start.
I have this code:
d = "e345a46be5"
for i in d:
print "x", i[::2],
and i come, x 43c48eaff x 43c48eaff x ..... . I will xe3,x45,xa4,x6b,xe5
The third parameter of the slice is the step size. This means you are taking the first, third, fifth... item.
I think the easiest way to do what you want is to use range:
d = "e345a46be5"
for i in range(0, len(d), 2):
print "x", d[i:i+2]
range(start, stop, step) => range(0,5,2) => [0, 2, 4]
This code that should work on python 2.7 and python 3:
for i in range(0,len(d),2):
print ("x", d[i:i+2])
Here we use i as an index instead as a specific letter as you did. and range (a,b,2) enables to go through a list starting with a, going to b excluded with step 2.

Resources