加入Python中的动态字符串分隔的列表元素

时间:2017-03-19 07:26:32

标签: python list

我想加入列表的元素,我希望它们用动态字符串分隔。一个例子将更好地解释:

import random

foodList = ['apples', 'pears' , 'strawberries' , 'nuts']

quantityList = ["1", "7", "20", "67"]

myJoinedFoods = '<li>' + random.choice(quantityList) + '</li>'.join(foodList)

print myJoinedFoods

这打印<li>1apples</li>pears</li>strawberries</li>nuts,但我期待:

apples<li>7</li>pears<li>20</li>strawberries<li>67</li>nuts<li>7</li>

如果我使用了像 myCustomSeparator 这样的简单/静态字符串,我希望列表中的每个连接项都会被动态字符串'<li>' + random.choice(quantityList) + '</li>'分隔开来。 p>

myJoinedFoods = '<li>55</li>'.join(foodList)

这将打印:

apples<li>55</li>pears<li>55</li>strawberries<li>55</li>nuts

4 个答案:

答案 0 :(得分:0)

您可以将列表理解与函数结合使用:

import random

foodList = ['apples', 'pears' , 'strawberries' , 'nuts']
quantityList = ["1", "7", "20", "67"]


def combine(value):
    return '{}<li>{}</li>'.format(value, random.choice(quantityList))

myJoinedFoods = ''.join([combine(item) for item in foodList])
print(myJoinedFoods)
# apples<li>20</li>pears<li>1</li>strawberries<li>1</li>nuts<li>20</li>

或者,使用单行时更短:

joinedFoods = ''.join(map(lambda x: '{}<li>{}</li>'.format(x, random.choice(quantityList)), foodList))
print(joinedFoods)

答案 1 :(得分:0)

您可以使用简单的方法:

import random

foodList = ['apples', 'pears' , 'strawberries' , 'nuts']
quantityList = ["1", "7", "20", "67"]
myJoinedFoods=''
for i in foodList:
  myJoinedFoods+=i+'<li>'+random.choice(quantityList)+'</li>'
print myJoinedFoods

另一种方式是格式化:

import random
foodList = ['apples', 'pears' , 'strawberries' , 'nuts']
quantityList = ["1", "7", "20", "67"]
myJoinedFoods=''
for i in foodList:
  myJoinedFoods+='{}<li>{}</li>'.format(food,random.choice(quantityList))
print myJoinedFoods 

哪个会提供所需的输出: apples<li>7</li>pears<li>20</li>strawberries<li>67</li>nuts<li>7</li>

答案 2 :(得分:0)

您有两项操作要做:

1 - 从quantityList

中选择随机数量

2 - 从foodList

中挑选食物

每次评估表达式时,两者都需要不同的值,因此您需要将它们的进程分开,例如:

>>> import random
>>> def pick_quatiy(l):
        return '<li>' + random.choice(l) + '</li>'
>>>
>>> s = ''
>>> for f in foodList:
        s += f + pick_quatiy(quantityList)


>>> s
'apples<li>67</li>pears<li>1</li>strawberries<li>20</li>nuts<li>7</li>'

因为如果您在random.choice方法中保留join方法,它将被评估一次,然后用于join您的列表,如下所示:

>>> pick_quatiy(quantityList).join(foodList)
'apples<li>20</li>pears<li>20</li>strawberries<li>20</li>nuts'

答案 3 :(得分:0)

你真的不需要作为分隔符,而是foodList中每个项目的附录。这可以使用str.join()来连接foodList中的项目+ separator()方法的返回值。

import random

foodList = ['apples', 'pears' , 'strawberries' , 'nuts']

quantityList = ["1", "7", "20", "67"]

def separator():
    return "<li>{}</li>".format(random.choice(quantityList))

''.join(x+separator() for x in foodList)
# apples<li>67</li>pears<li>1</li>strawberries<li>7</li>nuts<li>20</li>