Python adding outputs from a loop to an variable - python

The output I want to have is like:
the result is 8
the result is 16
the result is 24
the result is 32
the result is 40
So I do:
final = ''
for each_one in [1, 2, 3, 4, 5]:
result = 'the result is ' + str(each_one * 8)
final.join(result)
final.join('\n')
print final
But it doesn't work out. How can I adjust it?

final = ''
for each_one in [1, 2, 3, 4, 5]:
final += ('the result is ' + str( each_one * 8 )+'\n\n')
print final
I believe you are mixing join function with concatenation.
Not saying it would be impossible to do it with join,but
your code resembles usage of string concatenation.
Learn more about join here

You are misusing str.join; it actually works like
"x".join(["A", "B", "C"]) # => "AxBxC"
.join expects an iterable (ie a list or generator) of strings. If you pass it a single string, it will treat it as a list of characters:
"x".join("ABC") # => "AxBxC"
What you actually need to do is
lines = []
for num in [1, 2, 3, 4, 5]:
line = 'the result is ' + str(num * 8)
lines.append(line)
print('\n\n'.join(lines))
which gives
the result is 8
the result is 16
the result is 24
the result is 32
the result is 40

You can do the following:
print '\n\n'.join(['the result is {}'.format(each_one * 8) for each_one in range(1, 6)])

final = '\n'.join(["The result is " + str(num * 8) for num in [1,2,3,4,5]])
print(final) #or "print final" if Python 2
EDIT: if you want a line break in between each line, replace the '\n' with '\n\n'
EDIT#2:
The join method takes an iterable as its argument, which a list comprehension to a list counts. Any string calling the join method will concatenate the string in between the elements of the iterable in the join method argument. So a '\n' will appear concatenated to each element in the list I made via a list comprehension.
List comprehensions are key components of the language. They allow to dynamically create lists and can be useful for creating lists on-the-fly.
What it is saying, for each number in the list [1,2,3,4,5], do "The result is " + str(num * 8) on it, then take all the results and make a list out of it.
List comprehensions are great if you intend for a list object to be created. For example, you can use them to filter out a current list:
stringList = ["yes","no","yesterday"]
filtered = [item for item in stringList if "yes" in item]
#result is: ["yes", "yesterday"]
They are commonly misused as performing an operation over elements of an iterable, with no desire to have a list object. In that specific case, a simple for loop would be better.

There's another way to write this to be a bit easier and cleaner, if you'd like.
You can simply do:
for number in range(1,6):
print("The result is "+str(number*8))
Which outputs:
The result is 8
The result is 16
The result is 24
The result is 32
The result is 40

Related

How to convert a list of list of strings into integers

This is a list that I have [['1.0\n'],['2.0\n'],['3.0\n']] and I would like to convert them into integers 1 2 3 without comma separation and \n.
I'm not sure how to do this conversion as there's a list within a list and I don't really know how to get rid of \n altogether. Thanks.
if you want [[1], [2], [3]], you can try
lst = [['1.0\n'],['2.0\n'],['3.0\n']]
res = [[int(float(j.replace("\n", ""))) for j in i] for i in lst]
if you want [1, 2, 3], you can try
lst = [['1.0\n'],['2.0\n'],['3.0\n']]
res = [int(float(i[0].replace("\n", ""))) for i in lst]
Depends on whether you want rounding or not and or a new list. Is there a reason why you have a list in a list? But you'd do something like this
x = [['1.0\n'],['2.0\n']]
y = []
for item in x:
tmp = item[0].replace('\n','')
y.append(int(float(tmp)))
print(y)
There is a way:
ls=[['1.0\n'],['2.0\n'],['3.0\n']]
result=[]
for ll in ls:
[result.append(int(float(l.replace('\n','')))) for l in ll]
print(result)
Output: [1, 2, 3]
This code just works under this condition: [if every element in the list has \n]
Like Raya's answer, I use the int(float(l)) way, if every element has '.0', you can also use l.replace('\n','').replace('.0','').
Removing /n and consolidate to a single list
You could solve this with list comprehension.
list = [['1.0\n'], ['2.0\n'], ['3.0\n']]
my_list = [int(float(value[0].strip())) for value in list]
print(my_list)
Output: [1, 2, 3]
The main things to note in this solution are:
The nested lists are iterated through, selecting the first element of each with value[0].
Each iteration:
Value: '1.0\n' is stripped of the \n with value[0].strip()
Value: 1.0 is then converted to a float float(value[0].strip())
Value: 1 is then converted to a integer int(float(value[0].strip()))
Without comma separation
list = [['1.0\n'], ['2.0\n'], ['3.0\n']]
my_list = [int(float(value[0].strip())) for value in list]
my_string = " ".join(str(value) for value in my_list)
print(my_string)
Output: 1 2 3

How to change list of string to list of elements (numbers)?

When I use:
with open("test.txt") as file
read = csv.reader(file)
for i in read:
print(i)
and I have got something like that:
['[0', ' 0', ' 1', ' 0]']
and I need:
[0, 0, 1, 0]
Any advises please?
ad = ['[0', ' 0', ' 1', ' 0]']
for i in range(len(ad)):
ad[i] = int(ad[i].replace("[", "").replace("]", ""))
print ad
[0, 0, 1, 0]
Normally, the easiest solution would be a list comprehension where new = [int(a) for a in old]. However, in your case, the first and last elements of your list actually have brackets inside of them too.
Instead, you need to do something like:
new = [int("".join(filter(str.isdigit, a))) for a in old]
This is a pretty big one liner so lets break it down.
The list comprehension iterates through each element in your list (I called it old) and names it a
A is passed into the filter command with the function str.isdigit. This basically removes any character that isn't a digit. The issue with this, is that it returns an iterator and not a simple value.
To fix the iterator problem, I wrapped the filter command with a "".join() command to convert it to a simple string value. This string will only have the number.
Finally, we can wrap that entire thing with the int command which will transform your value into an int.
If you don't like the one-liner, it can also be done this way:
new = []
for a in old:
filtered = filter(str.isdigit, a)
num_str = "".join(filtered)
num.append(int(num_str))
It's the same thing but a bit more verbose.
def parseToInt(s):
...: return int((s.replace('[', '')).replace(']', ''))
list(map(lambda x: parseToINt(x), a))

Merge the two lists to get the desired output in python

List1 = [th,sk,is,bl]
List2=[ue,None,y,e]
Output = the sky is blue
Merge the two given lists and combine their elements to get the desired output.
Hi you could use zip and list comprehension to acomplish that:
List1 = ['th','sk','is','bl']
List2=['ue',None,'y','e']
temp = list(zip(List1, List2[::-1]))
words = [i[0]+i[1] for i in temp]
words = [''.join(item for item in i if item) for i in temp]
" ".join(item for item in words)
the List2[::-1] is to reverse the list.
Here's some I just wrote, not sure if it is the most pythonic but here goes:
List1 = ["th","sk","is","bl"]
List2 = ["ue",None,"y","e"]
concat = ""
for i in range(len(List1)):
concat += List1[i]
if List2[len(List2)-1-i]: concat += List2[len(List2)-1-i]
concat += " "
print(concat)
Expected output:
the sky is blue
I get:
>>> print(concat)
the sky is blue
>>>
But as mentioned, the purpose of this site is to teach and not do. Therefore:
List1 = ["th","sk","is","bl"]
List2 = ["ue",None,"y","e"]
concat = ""
We start by defining our lists and our "concatenation" variable, in which the parts are added.
for i in range(len(List1)):
This works round all items in List1 - I could have just typed 4, but this makes expandability in the future easy.
concat += List1[i]
List1 is in the correct order, and arrays start at 0. Hence first we have [0], the first item, to [3], the last.
if List2[len(List2)-1-i]: concat += List2[len(List2)-1-i]
Because there is a None in List2, we can’t concatenate a NoneType to a string. Therefore, we test if it is actually a value (just do “if string:”). If it is, we append it to our concatenation variable. The reason why I do len(List2)-1-i:
List2 is 4 long
We start with i=0
4-1-0 = 3
4-1-1 = 2
4-1-2 = 1
And finally,
4-1-3=0
You will notice that these are the same indexes we used in List1, but backwards which is what List2 is.
concat += “ “
We add a space in between words, and finally;
print(concat)
We print out our result

Correct way to save list of lists into string with multiple lines?

I have a list of lists and I want to print it into multiple lines. But I have to save it into a variable first which means I can't just print each element of the outer list.
def __str__(self):
string = ""
length = len(self.lst)
for index in range(length):
string += str(self.lst[index])
if (index != length-1):
string += "\n"
return string
This doesn't seem the best approach but it works.
Any suggestions?
How about this?
class LOL:
""" List of lists. """
def __init__(self, data):
self.lst = data
def __str__(self):
return ('[\n' +
'\n'.join(' ' + repr(sublist) for sublist in self.lst) +
'\n]')
lol = LOL([['a', 'b', 'c'], ['d', 'e'], [1, 2, 42]])
print(lol)
Output:
[
['a', 'b', 'c']
['d', 'e']
[1, 2, 42]
]
You might get what you want with something like join(). For example:
>>> print('\n'.join(', '.join(map(str, range(5))) for _ in range(3)))
0, 1, 2, 3, 4
0, 1, 2, 3, 4
0, 1, 2, 3, 4
A little bit shorter and more Pythonic and if you don't have a problem with new line in the end:
def __str__(self):
string = ""
for a_list in self.lst:
string += str(a_list) + "\n"
return string
The entire function body of your __str__ can be replaced by a single line of code as follows:
def to_string(self):
return '\n'.join(str(a) for a in self.lst)
I have renamed this function since you shouldn't use __str__ the way your are doing, as Karl pointed out. In general __str__ should return a short string that you wouldn't mind looking at on the console.
You may find that you only call to_string in one place. Once you realize that the function can be replaced by a single line, you may want to inline the entire expression instead of making a function call. It's idiomatic Python and therefore easy to read for someone with some experience.
This works OK:
# We supose all elements are strings, otherwise you must apply data transformation
my_list = [['a','b','v'], ['d','e','f'], ['g','h','i'], ['j','k','l']]
# Items separator: comma
sep = ','
# Converting each sublist in string
processed_sublists = [sep.join(item) for item in my_list]
# Lists (lines) separator: \n
sep = '\n'
result = sep.join(processed_sublists)
print(result)
Result:
a,b,v
d,e,f
g,h,i
j,k,l

How to remove the square brackets from a list when it is printed/output

I have a piece of code that does everything I need it to do and now I am making it look better and refining it. When I print the outcome, I find that the list in the statement is in square brackets and I cannot seem to remove them.
You can use map() to convert the numbers to strings, and use " ".join() or ", ".join() to place them in the same string:
mylist = [4, 5]
print(" ".join(map(str, mylist)))
#4 5
print(", ".join(map(str, mylist)))
#4, 5
You could also just take advantage of the print() function:
mylist = [4, 5]
print(*mylist)
#4 5
print(*mylist, sep=", ")
#4, 5
Note: In Python2, that won't work because print is a statement, not a function. You could put from __future__ import print_function at the beginning of the file, or you could use import __builtin__; getattr(__builtin__, 'print')(*mylist)
You could convert it to a string instead of printing the list directly:
print(", ".join(LIST))
If the elements in the list are not strings, you can convert them to string using either repr() or str() :
LIST = [1, "printing", 3.5, { "without": "brackets" }]
print( ", ".join( repr(e) for e in LIST ) )
Which gives the output:
1, 'printing', 3.5, {'without': 'brackets'}
If print is a function (which it is by default in Python 3), you could unpack the list with *:
>>> L = [3, 5]
>>> from __future__ import print_function
>>> print(*L)
3 5
You could do smth like this:
separator = ','
print separator.join(str(element) for element in myList)
Why don't you display the elements in the list one by one using the for loop instead of displaying an entire list at once like so:
# l - list
for i in range(0, len(l)):
print l[i],

Categories

Resources