简体   繁体   English

用不同的分隔符在 python 中打印数字列表

[英]Print a list of numbers in python with different delimiters

I need to print numbers in python as integers but with different delimiters depending on the position in the list if there is only one number in the list it should print like this: 1 otherwise if there are multiple numbers the following pattern is used:我需要将python中的数字打印为整数,但根据列表中的位置使用不同的分隔符,如果列表中只有一个数字,它应该像这样打印:1否则如果有多个数字,则使用以下模式:

5:7!11&13:17!19&23 5:7!11&13:17!19&23

I have the printing and the delimiter part correct but it is a list and it is a list of strings.我有正确的打印和分隔符部分,但它是一个列表,它是一个字符串列表。 Here is the code:这是代码:

primen = [5,7,11,13,17,19,23]
prime_out = []
prime_str = [str(item) for item in  primen]

prime_len = len(prime_str)
if (prime_len ==  0):
      print ("No Primes")
      exit()    

for k in range(0,prime_len): 
    if   k == prime_len - 1:
           prime_out.append(prime_str[k])
           print(prime_out)
    else:
          if  lng ==  0:
                prime  =  prime_str[k] + ":"  
                prime_out.append(prime)
                lng =  lng + 1                 
          elif lng == 1:
                prime  =  prime_str[k] + "!"
                prime_out.append(prime)
                lng = lng + 1                     
          elif  lng ==  2:
                prime  =   prime_str[k] + "&"
                prime_out.append(prime)                   
                lng = 0
  

and my output looks like this: ['5:', '7!', '11&', '13:', '17!', '19&', '23'] How do I get it to look like I need it?我的输出看起来像这样: ['5:', '7!', '11&', '13:', '17!', '19&', '23'] 我如何让它看起来像我需要的它?

You can use "join" like this:您可以像这样使用“加入”:

output = ['5:', '7!', '11&', '13:', '17!', '19&', '23']
print("".join(output))

And the result is:结果是:

5:7!11&13:17!19&23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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