英文:
Creating a string with separators from a list of numbers using Python3
问题
Here is the translated code:
我有一个数字列表:
list1 = [1, 2, 3, 4]
我想创建如下的字符串:
Contains([saleID],"1") OR
Contains([saleID],"2") OR
Contains([saleID],"3") OR
Contains([saleID],"4")
我尝试了以下代码:
print('Contains([saleID],"' + '" OR Contains([saleID],'.join(str(x) for x in list1) + '")')
Hope this helps!
英文:
I have a list of numbers:
> list1 = [1, 2, 3, 4]
I would like to create a string as follows:
Contains([saleID],"1") OR
Contains([saleID],"2") OR
Contains([saleID],"3") OR
Contains([saleID],"4")
I tried the following code:
print('Contains([saleID],"'.join(str(x) for x in list1).join('" OR'))
But I get the following output:
"1Contains([saleID],"2Contains([saleID],"3Contains([saleID],"4 1Contains([saleID],"2Contains([saleID],"3Contains([saleID],"4O1Contains([saleID],"2Contains([saleID],"3Contains([saleID],"4R
Please advise
答案1
得分: 1
c = '包含([saleID], "'
print(c + ('") OR\n'+c).join([str(x) for x in list1]) + '")')
英文:
c = 'Contains([saleID],"'
print(c + ('") OR\n'+c).join([str(x) for x in list1]) + '")')
答案2
得分: 1
x.join(lst)
使用 x
作为分隔符连接 lst
中的元素。根据这个信息,你可以使用 x = '' OR\n''
,因为这是要重复的部分。lst
中的元素可以包含每行的其余部分,即 'Contains([saleID], "{num}")'
。
这个操作分为两个部分:
- 将数字格式化成字符串
'Contains([saleID], "{num}")'
,得到一个包含四个字符串的列表,如下所示:
lst = [f'Contains([saleID], "{num}")' for num in list1]
['Contains([saleID], "1")',
'Contains([saleID], "2")',
'Contains([saleID], "3")',
'Contains([saleID], "4")']
- 使用
x
连接列表中的所有格式化字符串,即x.join(lst)
:
result = '' OR\n''.join(lst)
'Contains([saleID], "1") OR\nContains([saleID], "2") OR\nContains([saleID], "3") OR\nContains([saleID], "4")'
打印 result
以查看我们得到了所需的值:
Contains([saleID], "1") OR
Contains([saleID], "2") OR
Contains([saleID], "3") OR
Contains([saleID], "4")
当然,你也可以在一行中完成所有操作:
result = '' OR\n''.join(f'Contains([saleID], "{num}")' for num in list1)
英文:
x.join(lst)
joins the elements of lst
using x
as a separator. Knowing this, you want to use x = ' OR\n'
because that's what is repeated. The elements of lst
can contain the rest of each line, i.e. 'Contains([saleID],"{num}")'
There are two parts to this operation:
- Format the number into the string
'Contains([saleID],"{num}")'
, which gives a list containing four strings as shown below:
>>> lst = [f'Contains([saleID],"{num}")' for num in list1]
['Contains([saleID],"1")',
'Contains([saleID],"2")',
'Contains([saleID],"3")',
'Contains([saleID],"4")']
And,
- Join all the formatted strings in this list with
' OR\n'
>>> result = ' OR\n'.join(lst)
'Contains([saleID],"1") OR\nContains([saleID],"2") OR\nContains([saleID],"3") OR\nContains([saleID],"4")'
Print result
to see that we have the desired value:
Contains([saleID],"1") OR
Contains([saleID],"2") OR
Contains([saleID],"3") OR
Contains([saleID],"4")
Of course, you can do this all in a single line with:
>>> result = ' OR\n'.join(f'Contains([saleID],"{num}")' for num in list1)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论