简体   繁体   中英

Python: Combining two strings and selecting unique elements out of it

I would like to state that I am new to programming and to Python. I did try doing research before posting this question but my lack of knowledge of even basics did not help yielding any results, thus requiring me to ask here.

I have two strings which are like:

 str_a = "100,101,105,304"
 str_b = "400,500,101"

I need to combine these strings into one so I use:

  str_c = str_a + "," + str_b

And my issue starts here. In this new string, where there are elements (numbers) separated by a comma, I want to have each item listed only once. The order of numbers do not matter but if it was ascending, it would be pretty amazing.

What can I do to combine these two, having each number listed once, if possible ordered small to large?

Since these are strings, I am not even sure if I can iterate through?

Your help will be greatly appreciated, thanks in advance.

Try this:

str_a = "100,101,105,304"
str_b = "400,500,101,2000"
l = str_a.split(',') + str_b.split(',')
print ','.join(sorted(set(l), key=int))

The output is:

100,101,105,304,400,500,2000

Thanks Oren for the comment! I've added key=int as an extra argument to sorted to compare the elements of the list as integers instead of strings. This argument allows one to specify a function of one argument that will be called on each element of the list to extract a comparison key. In our case, we use int to convert each element to an integer.

You want to split the strings up using the split method:

str_a_vals = str_a.split(",")
str_b_vals = str_b.split(",")

Then do:

allVals = str_a_vals
allVals += str_b_vals

str_c = ",".join(set(allVals))

If you want to do stuff like sorting and selecting numbers, storing the numbers in strings is probably not the right approach. Try using lists, like this:

list_a = [100,101,105,304]
list_b = [400,500,101]

Getting the unique elements of the combined lists would be as easy as

unique = set(list_a + list_b)

and getting them in ascending order is

ascending = sorted(list_a + list_b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM