Python print list of sets without brackets [duplicate] - python

This question already has answers here:
Removing set identifier when printing sets in Python
(5 answers)
Closed 9 years ago.
I have a list of sets (using Python).
Is there a way to print this without the "set([])" stuff around it and just output the actual values they are holding?
Right now I'm getting somthing like this for each item in the list
set(['blah', 'blahh' blahhh')]
And I want it to look more like this
blah,blahh,blahhh

Lots of ways, but the one that occurred to me first is:
s = set([0,1])
", ".join(str(e) for e in s)
Convert everything in the set to a string, and join them together with commas. Obviously your preference for display may vary, but you can happily pass this to print. Should work in python 2 and python 3.
For list of sets:
l = [{0,1}, {2,3}]
for s in l:
print(", ".join(str(e) for e in s))

I'm assuming you want a string representation of the elements in your set. In that case, this should work:
s = set([1,2,3])
print " ".join(str(x) for x in s)
However, this is dependent on the elements of s having a __str__ method, so keep that in mind when printing out elements in your set.

Assuming that your list of sets is called set_list, you can use the following code
for s in set_list:
print ', '.join(str(item) for item in s)
If set_list is equal to [{1,2,3}, {4,5,6}], then the output will be
1, 2, 3
4, 5, 6

Related

How do I change a singular element of a python list to a string [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 10 months ago.
Say I have a python list with 5 elements; list = ['a','b','c','d','e']. And I want to change it into 5 different strings so that each element is its own string, for example,
str1 = a str2 = b str3 = c str4 = d str5 = e
How would that be done?
Note: I would want it to be done autonomously if possible as the number of elements in a list is variable according to the data that is input at the beginning of the original code.
list_ = ['a','b','c','d','e']
You can use something called list unpacking, that you can do this way:
a, b, c, d, e = list_
As #Mark told you in the comments...
I'd be curious to know when str1, str2, etc. is preferable to s[1] , s[2]. It sounds like you are about to make a mistake you will later regret.
...you should avoid this approach.
If you don't know the lenght, you should read this, which suggests you to use the * star operator...
first, second, *others, third, fourth = names
...until you have the whole list unpacked.
Since you don't want to write an hell of if/elif/else over the lenght, I would suggest you to use exec to create variables on fly, even if (like Mark said) it's a bad idea.
I really want you to get that this is a bad idea, but you can use unpacking for useful scopes, in this case I would suggest you to read this, this and the respective PEP.

convert list into string? [duplicate]

This question already has answers here:
How to convert list to string [duplicate]
(3 answers)
Closed 2 years ago.
Here is my list ['k:1','d:2','k:3','z:0'] now I want to remove apostrophes from list item and store it in the string form like 'k:1 , d:2, k:3, z:0' Here is my code
nlist = ['k:1','d:2','k:3','z:0']
newlist = []
for x in nlist:
kk = x.strip("'")
newlist.append(kk)
This code still give me the same thing
Just do this : print(', '.join(['k:1','d:2','k:3','z:0']))
if you want to see them without the apostrophes, try to print one of them alone.
try this:
print(nlist[0])
output: k:1
you can see that apostrophes because it's inside a list, when you call the value alone the text comes clean.
I would recommend studying more about strings, it's very fundamental to know how they work.
The parenthesis comes from the way of representing a list, to know wether an element is a string or not, quotes are used
print(['aStr', False, 5]) # ['aStr', False, 5]
To pass from ['k:1','d:2','k:3','z:0'] to k:1 , d:2, k:3, z:0 you need to join the elements.
values = ['k:1','d:2','k:3','z:0']
value = ", ".join(values)
print(value) # k:1, d:2, k:3, z:0
What you have is a list of strings and you want to join them into a single string.
This can be done with ", ".join(['k:1','d:2','k:3','z:0']).

How to add comma in print statement in Python [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I print variable and string on same line in Python? [duplicate]
(18 answers)
Closed 5 years ago.
I'm new to python and learning how to code.
I'm printing last element of my list and sum of the list as-
print list[-1],sum
But the output is separated by " " and not separated by ",".
Any idea how to separate it by comma?
I'm using Python 2.7
Include it in quotes, like this:
print str(list[-1]) + "," + str(sum)
Enclosing them in str() is unnecessary if list[-1] and sum are strings.
In general, symbols are interpreted as Python symbols (for example, names like sum are interpreted as variable or function names). So whenever you want to print anything as is, you need to enclose it in quotes, to tell Python to ignore its interpretation as a Python symbol. Hence print "sum" will print the word sum, rather than the value stored in a variable called sum.
You'll have to compose that together into a string. Depending on what version of Python you're using, you could either do:
print "{},{}".format(list[-1], sum)
or
print "%s,%s" % (list[-1], sum)
If you were using Python3.6+, there would be a third option:
print(f"{list[-1]},{sum}")
Use the sep keyword argument:
print(list[-1], sum, sep=',')
You can use str.format() and pass whatever variables you want to get it formatted, for example:
x = 1
z = [1, 2, 3]
y = 'hello'
print '{},{},{}'.format(x, z[-1], y)
# prints: 1,3,hello

Algorithm for sorting a list in python does not work properly [duplicate]

This question already has answers here:
How to sort python list of strings of numbers
(4 answers)
Closed 8 years ago.
I am using the following function in order to sort a list in an increasing order. However, while my function works for lists such as: [1,5,6,9,3] or [56,43,16,97,45], it does not work for lists of the form: [20,10,1,3,50].
In such cases, the computer seems to consider that 3>20 and 3>10 and 3 ends up right before 50 (second to last) in the "sorted" list I get. More precisely the result I get is: [1,10,20,3,50].
Here is my code:
def function_sort(L):
for j in range(len(L)):
min=j
for i in range(j+1,len(L)):
if L[i]<L[min]:
min = i
if(min != j):
L[j],L[min] = L[min],L[j]
print L
return L
Could anyone please explain me what is going on?
It sounds like your list consists of strings rather than integers, and you end up getting the elements sorted lexicographically.
By way of illustration, consider the following:
>>> 10 < 2
False
>>> '10' < '2'
True
To fix the issue, convert the elements to integers before sorting:
L = map(int, L)
P.S. I recommend against using min as a variable name since it shadows the built-in function min().

How to pass a list containing a single string in python? [duplicate]

This question already has an answer here:
Convert list items to tuple
(1 answer)
Closed 9 years ago.
In Python, how do I pass a list that contains only one string?
For example:
def fn(mylist): return len(mylist)
print fn(('abc', 'def')) # prints 2
print fn(('abc')) # prints 3
I want it to print 1 for the one string in the list ('abc') but instead it prints 3 for the 3 characters of the string.
That's a tuple, not a list. To make a one-tuple, do this:
print fn(('abc',))
To make a list of length one, do this:
print fn(['abc'])
In your scenario, I think a list would be more appropriate. Use lists when you have a bunch of the same elements of the same type, and tuples when you have a “record”, or some elements of possibly different types and you don't need to add or remove any entries. (Lists often contain tuples.)
fn(['abc'])
passes a list
fn(('abc'))
passes a string in parentheses which are ignored.
As other posters have pointed out
fn(('abc', ))
passes a tuple.
They are actually called tuples, and you can create a tuple of length one like so:
print fn(('abc',))
when you use ('abc', 'def') it means you are passing a tuple.
A tuple with single element can be declared as ('abc',) .
*note the trailing comma.
passing value as ('xyz') or 'xyz' are same.
So python function len('string') returns the number of character.
also , len(iteratable) gives count of elements in the iteratable.
So, you should use fn(['abc']) or fn(('abc',)) to get the required answer.

Categories