a=[2]
a.append(3)
print (a)
result is [2, 3].
I want to have a output 23 instead of [2,3]. Any suggestions?
When you do something like a = [2] in Python, it creates a list out of it with one element 2 in the list.
You seemingly want string operations. There are two ways to do this. Firstly,
a = '2'
a = a + '3'
print (a)
Another way, probably the one which you're looking for, is converting the list into a string, as follows.
a = [2]
a.append(3)
b = ''.join(str(x) for x in a)
print (b)
Here is a brief explanation of the second approach:
You forcibly typecast each element of the list a to string, and then use join method to convert the list to string. Essentially, first the list [2, 3] is converted to ['2', '3'] and then join is used.
Edit:
Another approach, to better explain what I said above,
a = [str(2)]
a.append(str(3))
b = ''.join(a)
print (b)
Since the numbers are stored as ints instead of strings it makes it slightly more difficult as you will need to cast them to strings.
a=[2]
a.append(3)
print("".join(str(x) for x in a))
This will give your desired output. If you want the output to be an int then you can just cast it back.
Related
So in Python, I have a matrix as follows:
theMatrix = [["String", "0"],["String2", "1"]]
And I would like to convert all numbers at index 1 of each list to an integer.
Result:
theMatrix = [["String", 0],["String2", 1]]
This needs to work for more than just the two lists:
eg. theMatrix = [["String", 0],["String2", 1],["String3", 2],["String4", 3]]
please elaborate on programming language and will there be more element in the inner list or they are always tuples? u want to convert every integers in string format to int or just the 2nd item in inner list? what is the intention or usage of this data structure. what you may need to consider is a dictionary or hash table. Just give a thought it will fit for ur solution.
For python language and you may have more elements in inner list and always position 1 has to be changed, then the following code may help
for innerList in theMatrix:
if len(innerList) > 1:
value = int(innerList[1])
innerList[1] = value if value >= 0 else 0
theMatrix = [["String", '0'],["String2", '1'],["String3", '2'],["String4", '3']]
#iterate the list of lists and convert the int string to int.
[[e[0],int(e[-1])] for e in theMatrix]
Out[222]: [['String', 0], ['String2', 1], ['String3', 2], ['String4', 3]]
I use python 2.7, I want to reduce and optimize this code lines but I have a problem, could anybody help me please?
I have this list B = [[0, Act1, XX1, u'P-Um'],.....[0, Act100, ZZ30, u'D- MOM']]
I want to take only the 4th value from B
Take just the part after hyphen and the space which is sometimes
Bring back to B
Right now I wrote this code
for i in range(len(B)):
x.append(B[i][3])
A = [i.split('-',1)[1] for i in x]
#A=[u'Um', u' LY', u' NO', ......, u' MOM']
for i in range(len(B)):
A[i].lstrip()
p = []
for i in range(len(B)):
p.append(A[i].lstrip())
for i in range(len(B)):
B[i][3] = p[i]
When I try to make it shorter at follows I have two errors.
#Short version
for i in range(len(B)):
x.append(B[i][3])
A = [i.split('-',1)[1], x] #Error:AttributeError: 'int' object has no attribute 'split'
B[i][3].append(A[i].lstrip()) #Error:AttributeError: 'unicode' object has no attribute 'append'
I try many ways to solve the errors but still not working. Could you help please? Do you think is possible to make the top part shorter without errors?
Thank you very much in advance.
You can use a list comprehension:
B=[[B_element[0],B_element[1],B_element[2],B_element[3].split('-',1)[1].lstrip()] for B_element in B]
I'm not seeing the many ways you've tried, but your code does have a handful of missteps. Even after correcting the indentation errors, your first variant iterates over an index which you don't need four times, and strips every entry twice (only using the result the second time). The second version fails firstly because that index isn't the entry and secondly because you're trying to alter a string instead of replacing it.
A=[]
x=[]
for Bi in B:
Bi3 = Bi[3]
part = Bi3.split('-',1)[1].lstrip()
x.append(Bi3) # Original B[i][3] data
A.append(part) # What is this for?
Bi[3] = part # replaces B[i][3]
If you actually need performance, it's quite likely a regular expression might extract the part more efficiently than the split/strip combination, since those functions create new strings for each call.
You don't have to index the items of B to iterate over them. This may help.
>>> Act1 = XX1 = Act100 = ZZ30 = None # simply to avoid NameError exceptions
>>> B = [[0, Act1, XX1, u'P-Um'],[0, Act100, ZZ30, u'D- MOM']]
>>> result = [b[3].split('-')[1].strip() for b in B]
>>> result
['Um', 'MOM']
result is a list, produced by taking element 3 of each item in B, splitting it on the '-' and stripping leading and trailing spaces from element 1 of the split string. The technique I have used is known as a list comprehension.
If you then want to replace the fourth elements with these new values, one way to achieve this is as follows.
>>> final = []
>>> for b, r in zip(B, result):
... final.append([b[0], b[1], b[2], r])
...
>>> final
[[0, None, None, 'Um'], [0, None, None, 'MOM']]
Then just replace B with final:
>>> B = final
Hear me out, I do not simply want someone to solve this problem for me. I know it is not 100% complete yet, but currently when I run the program I get an error about "Can't convert 'list' object to str implicitly" I'm looking for help on how to fix this and why it is does this.
Here is the problem
Write code to print out each thing in the list of lists, L, with a '*' after it like
1*2*3*4*...8*a*b*c*d*
This requires knowing the print statement and using the end or sep argument option
Here is my list, sorry for not putting it in earlier
L = [[1,2,3,4],[5,6,7,8],['a','b','c','d']]
Here is my code at the moment
def ball(x): #random function name with one parameter
q = '' #
i = 0
if type(x) != list: #verifies input is a list
return"Error"
for i in x: #Looks at each variable in list
for j in i: #Goes into second layer of lists
q = q + j + '*'
print(q)
The reason for your error
"Can't convert 'list' object to str implicitly"
is that you're using the wrong variable in your nested for loops. Where you're concatenating values to your q variable, you mistakenly put q = q + i when you wanted q = q + j. You also will want to cast the value of j as a string so it can be concatenated with q. In order to get your desired output, you can simply add an asterisk into that statement - something like the following: q = q + str(j) + '*'. On a completely unrelated note, your else statement that just has "Mistake" in it should be removed completely - it doesn't follow an if and it doesn't actually return or assign to a variable.
Note that this is not the most elegant way to go about solving this problem. I agree with ilent2 that you should take a look at both list comprehension and the str.join() method.
If you have a list of strings,
myList = ['a', '123', 'another', 'and another']
You can join them using the str.join function:
Help on method_descriptor:
join(...)
S.join(iterable) -> string
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
myString = '#'.join(myList)
If your list contains mixed types or non-strings you need to convert each item to a string first:
anotherList = [1, 2, 'asdf', 'bwsg']
anotherString = '*'.join([str(s) for s in anotherList])
You might want to read about list comprehension or more about the join function. Note, the above doesn't print the output (unless you are using the interactive console), if you want the output to be printed you will need call print too
print myString
print anotherString
And, if you are working with lists-of-lists you may need to change how you convert each sub-list into a string (depending on your desired output):
myListList = [[1, 2, 3, 4], [2, 3, 6, 5], [6, 4, 3, 1]]
myOtherString = '#'.join(['*'.join([str(s) for s in a]) for a in myListList])
The last line is a little complicated to read, you might want to rewrite it as a nested for loop instead.
I am trying to add together two lists so the first item of one list is added to the first item of the other list, second to second and so on to form a new list.
Currently I have:
def zipper(a,b):
list = [a[i] + b[i] for i in range(len(a))]
print 'The combined list of a and b is'
print list
a = input("\n\nInsert a list:")
b = input("\n\nInsert another list of equal length:")
zipper(a,b)
Upon entering two lists where one is a list of integers and one a list of strings I get the Type Error 'Can not cocanenate 'str' and 'int' objects.
I have tried converting both lists to strings using:
list = [str(a[i]) + str(b[i]) for i in range(len(a))]
however upon entering:
a = ['a','b','c','d']
b = [1,2,3,4]
I got the output as:
['a1','b2','c3','d4']
instead of what I wanted which was:
['a+1','b+2','c+3','d+4']
Does anyone have any suggestions as to what I am doing wrong?
N.B. I have to write a function that will essentially perform the same as zip(a,b) but I'm not allowed to use zip() anywhere in the function.
Zip first, then add (only not).
['%s+%s' % x for x in zip(a, b)]
What you should do
You should use
list = [str(a[i]) +"+"+ str(b[i]) for i in range(len(a))]
instead of
list = [str(a[i]) + str(b[i]) for i in range(len(a))]
In your version, you never say that you want the plus character in the output between the two elements. This is your error.
Sample output:
>>> a = [1,2,3]
>>> b = ['a','b','c']
>>> list = [str(a[i]) +"+"+ str(b[i]) for i in range(len(a))]
>>> list
['1+a', '2+b', '3+c']
When using a list comprehension, is the order of the new list guaranteed in any way? As a contrived example, is the following behavior guaranteed by the definition of a list comprehension:
>> a = [x for x in [1,2,3]]
>> a
[1, 2, 3]
Equally, is the following equality guaranteed:
>> lroot = [1, 2, 3]
>> la = [x for x in lroot]
>> lb = []
>> for x in lroot:
lb.append(x)
>> lb == la
True
Specifically, it's the ordering I'm interested in here.
Yes, the list comprehension preserves the order of the original iterable (if there is one).
If the original iterable is ordered (list, tuple, file, etc.), that's the order you'll get in the result. If your iterable is unordered (set, dict, etc.), there are no guarantees about the order of the items.
Yes, a list is a sequence. Sequence order is significant.
It has been a while, but since I came up with a similar question myself recently, and needed a bit more explanation to understand what this comes down to exactly, I'll add my two cents, may it help someone else in the future! :)
More specifically this is about the order of values resulting from a list comprehension operation.
Imagine you have the following list:
list_of_c = [a, b, c, d, e]
I want to round the variables in that list using the following list comprehension:
list_of_d = [round(value, 4) for value in list_of_c]
My question was whether this would mean that the order resulting from the list comprehension would be the following:
list_of_d = [round_a, round_b, round_c, round_d, round_e]
And the answer I received very kindly from #juanpa.arrivillaga , was that indeeded, YES that was the case!