This question already has answers here:
Access multiple elements of list knowing their index [duplicate]
(11 answers)
Closed 12 months ago.
So i want to take any integer as an input and get an output based on arrays like this:
Input: 012346
array = ["a","b","c","d","e","f","g"]
Output: abcdeg
how would i do that?
Use a comprehension. Convert input string to a list of characters then get the right element from array:
inp = '012346'
# For inp to be a string in the case of inp is an integer
out = ''.join([array[int(i)] for i in str(inp)])
print(out)
# Output
abcdeg
Update
How i would treat numbers above 10 since they would get broken down to 1 and 0
Suppose the following input:
inp = '1,10,2,3'
array = list('abcdefghijklmn')
out = ''.join([array[int(i)] for i in inp.split(',')])
print(out)
# Output
'bkcd'
Looks like operator.itemgetter could do the job.
>>> from operator import itemgetter
>>> itemgetter(0, 1, 2, 3, 4, 6)(array)
('a', 'b', 'c', 'd', 'e', 'g')
The input function in Python always returns a string, unless you cast it into another type. So you can loop over the digits of this string, cast the digits individually into an integer, and use that to fetch the letters from the list and concatenate them:
str = “”
data = input(“Data? “)
for digit in data:
str += array[int(digit)]
Related
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Convert all strings in a list to int
(10 answers)
Closed last month.
l = list(input('enter a list:'))
print(l)
In this program 'l' is the variable which will take input from the user and return it as a list.
But when 'l' is printed it returns the integer as a string.
Output:
enter a list: 12345
['1', '2', '3', '4', '5']
Process finished with exit code 0
What is the problem with this code?
You can call int() to convert the characters to integers.
l = list(map(int, input("Enter a list:")))
print(l)
If you enter 12345 this will print [1, 2, 3, 4, 5]
When you input 12345, you're inputting a string - not an integer.
When you convert a string to a list the list will be comprised of the string's constituent parts - i.e., all of its characters.
You're asking the user to 'enter a list' and that's exactly what's happening - a list of characters
All input is inputted as a string, and it's up to you to cast/convert it to a different type if you need it. If you know the input is a string of digit, you can treat it as an iterable and explicitly convert every character to a digit:
mylist = [int(i) for i in input('Enter a series of digits: ')]
If you want to create a list of integers from the user's input, you can use a list comprehension or for loop to convert each character to an integer, something like this-
l = [int(i) for i in input('Give input:')]
print(l)
Why your solution is not working: In Python, the input function returns a string, which is a sequence of characters. When you pass the string to the list function, it creates a list of the individual characters in the string. For example, if you enter the string "12345", the list will be ['1', '2', '3', '4', '5'].
I am trying to convert a line from a text file into a list. The contents of the test file are:
1 2 3 4 f g
I have read the contents into a list lst = ['1','2','3','4','f','g']. I want to remove 'f' and 'g' (or whatever characters they may be) and convert all the remaining elements to int type. How can I achieve this?
Instead of removing, rather build a new list. Python is more efficient when just appending items to a list. Here we try to convert i to an int - if it is convertable then it reads as some base-10 number, with possible + or - sign. If it does not match, then int(i) throws a ValueError exception which we just ignore. Those values that were correctly converted will be appended to a new result list.
result = []
for i in elements:
try:
result.append(int(i))
except ValueError:
pass
This is a good time for a list comprehension. Convert to int only if isnumeric()
arr = [int(x) for x in arr if x.isnumeric()]
Try checking if each character can be converted into a character:
arr = ['1', '2', '3', '4', 'f', 'g']
for c, char in enuemrate(arr[:]):
try:
arr[c] = int(char)
except ValueError:
del arr[c]
print(arr)
You can use the built-in Python method isalpha().
The method returns “True” if all characters in the string are alphabets, Otherwise, it returns “False”.
I'm assuming that there are no alpha-numeric elements in your list, and your list contains either digits or alphabets. You could try something like this:
elements = [1, 2, 3, 4, 'f', 'g']
for element in elements:
if element.isalpha():
elements.remove(element) #Removing the alphabets
#Converting the remaining elements to int
elements = [ int(x) for x in elements ]
This question already has answers here:
Creating a function that can convert a list into a dictionary in python
(3 answers)
Closed 5 years ago.
I'm trying to write a function that splits a string and converts it into a dictionary (and if possible, allows me to assign values to each string that's converted into a key). For instance, if I have sample input of mystring = 'abcd' I want to split this into individual letters, convert it into a dictionary and then assign each of the keys a given value (e.g. 1, 2, 3, 4). So the sample output I'm looking for would be {1: 'a', 2: 'b', 3: 'c', 4: 'd'} I know that something like enumerate() is an effective way of converting a list into a dictionary, for instance:
dict(enumerate(mylist,1))
list_conversion = lambda x: dict(enumerate(x,1))
But I'm not sure how to do something similar for a string.
Since strings are iterable the same way as lists, the exact same thing will work for strings:
>>> mystring = 'abcd'
>>> dict(enumerate(mystring, 1))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
The answer for such things is Collections
https://docs.python.org/2/library/collections.html - python 2
https://docs.python.org/3.5/library/collections.html - python 3
Default dict is a great way to handle things like creating key- values
This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Printing list elements on separate lines in Python
(10 answers)
Closed 5 years ago.
So, I have a project in which I have a list of strings:
outputs = ['cow', 'chicken', 'pig']
I need to turn them into a string, with each value separated by a newline, like so:
cow
chicken
pig
I found a solution at python list to newline separated value, but it uses a list like this:
outputs = [['cow'], ['chicken'], ['pig']]
and whenever I run:
answer = "\n".join(map(lambda x: x[0], outputs))
print(answer)
It returns 'c', as is the case with all the other answers in that question.
You can join a list of strings by another string by simply using:
str = "\n".join(outputs)
Your problem is that when you did:
map(lambda x: x[0], outputs)
You created an iterable consisting of the first letter of each element in outputs:
>>> outputs = ['cow', 'chicken', 'pig']
>>> list(map(lambda x: x[0], outputs))
['c', 'c', 'p']
Your over-thinking this. In this case, you don't even need to use map. You can simply use str.join:
'\n'.join(outputs)
This question already has answers here:
What is the difference between Python's list methods append and extend?
(20 answers)
Closed 5 years ago.
I'm new to python. I tried to store bunch of strings to an array and at the end print out the array, however it print out as a long list of characters. here is my code:
user_with_no_records = [""]
for user_test_docs in json_data['results']:
... do something here ...
user_with_no_records.extend(user_test_docs['userId'].replace("'", '"'))
...
pprint(user_with_no_records)
instead of print out :
"1234-4a20-47c0-b23c-a35a", "53dd-4120-4249-b4f6-ebe2"
it print out
"1","2","3","4","-","a","2","0"....
a.extend(b) is for extending list a by concatenating another sequence b onto it. When b is a string, and you force it to be interpreted as a sequence, it is interpreted as a sequence of individual characters. A simple example of this is:
>>> b = 'Hello'
>>> list(b)
['H', 'e', 'l', 'l', 'o']
Instead, you clearly want to do a.append(b), i.e. insert the entire string b as a single new item at the end of a.