如何在数组中只有两个项的情况下删除逗号。

huangapple go评论78阅读模式
英文:

Comma-code excerise how to remove comma with only two items in array

问题

PS 这本书还没有涵盖到 join 函数,所以你必须使用 if、elif 和 else。

所以在《自动化繁琐的工作》中的逗号代码练习中,你需要创建一个列表,并在每个项目之间使用逗号进行打印,在最后一个项目之前添加“和”。

示例:

spam = ['apples','bana', 'apple']
def commacode(passedlist):
    stringy = ''
    if len(passedlist) == 1:
        stringy += str(passedlist[0])
        return stringy
    for i in range(len(passedlist)-1):
        stringy += str(passedlist[i]) + ', '
        # 将所有项目添加到字符串中,除了最后一个
    stringy += 'and ' + str(passedlist[len(passedlist)-1])
    # 在 'and' 之后将最后一个项目添加到字符串中
    return stringy
print(commacode(spam))

输出结果为:apples, bana, 和 apple。

然而,如果只有两个项目,它将打印出 apples, and bana,这在语法上是不正确的。所以我的问题是,我该如何使它正确?我尝试添加了一个 elif 和 else 语句,但它破坏了我的代码,我没有保存它来向你们展示(抱歉)。

英文:

PS The book doesn't reach the join function yet so you have to use if,elif and else

So in the comma code exercise in automate the boring stuff you have to create a list and print it out using commas between each item and add 'and' before the last item.

Example

spam = ['apples','bana', 'apple']
def commacode(passedlist):
    stringy = ''
    if len(passedlist) == 1:
        stringy += str(passedlist[0])
        return stringy
    for i in range(len(passedlist)-1):
        stringy += str(passedlist[i]) + ', '
        # adds all except last item to str
    stringy += 'and ' + str(passedlist[len(passedlist)-1])
    # adds last item to string, after 'and'
    return stringy
print(commacode(spam)) 

outputs apples , bana, and apple.

However if it is only two items it would print out apples, and bana which isnt grammatically correct. So my question is how would I make it correct I tried adding a elif and else statement but it broke my code and I didn't save it to show you guys(sorry)

答案1

得分: 1

以下是您要翻译的内容:

The joined string should starts with the first element, then build itself with all elements from 1 to second-to-last (there may be 0 of them). Returns it if the list only contains 1 element, or add ` and {last_element}` otherwise.

```py
def join_to_human_readable_list(elements):
  joined = str(elements[0])

  for element in elements[1:-1]:
    joined += f', {element}';

  return joined if len(elements) == 1 else f'{joined} and {elements[-1]}';

The function above will raise an IndexError if elements has a length of 0, if this is not what you need and you want to return an empty string instead, I believe you know how to do so.

Also, do remember to use good names. "Readability counts."

Try it:

print(join_to_human_readable_list(['apples']))                     # apples
print(join_to_human_readable_list(['apples', 'banana']))           # apples and banana
print(join_to_human_readable_list(['apples', 'banana', 'apple']))  # apples, banana and apple

<details>
<summary>英文:</summary>

The joined string should starts with the first element, then build itself with all elements from 1 to second-to-last (there may be 0 of them). Returns it if the list only contains 1 element, or add ` and {last_element}` otherwise.

```py
def join_to_human_readable_list(elements):
  joined = str(elements[0])

  for element in elements[1:-1]:
    joined += f&#39;, {element}&#39;

  return joined if len(elements) == 1 else f&#39;{joined} and {elements[-1]}&#39;

The function above will raise an IndexError if elements has a length of 0, if this is not what you need and you want to return an empty string instead, I believe you know how to do so.

Also, do remember to use good names. "Readability counts."

Try it:

print(join_to_human_readable_list([&#39;apples&#39;]))                     # apples
print(join_to_human_readable_list([&#39;apples&#39;, &#39;banana&#39;]))           # apples and banana
print(join_to_human_readable_list([&#39;apples&#39;, &#39;banana&#39;, &#39;apple&#39;]))  # apples, banana and apple

答案2

得分: 0

你工作太辛苦了。问题相当简单:

spam = ['apples', 'bananas', 'grapes']
def commacode(passedlist):
    return ', '.join(passedlist[:-1]) + ' and ' + passedlist[-1]
print(commacode(spam))

如果只有一个项目,则会失败,所以读者的练习是使用简单的if来检查并处理这种情况。

英文:

You're working too hard. The problem is pretty easy:

spam = [&#39;apples&#39;,&#39;bananas&#39;, &#39;grapes&#39;]
def commacode(passedlist):
    return &#39;, &#39;.join(passedlist[:-1]) + &#39; and &#39; + passedlist[-1]
print(commacode(spam)) 

This fails if there's only one item, so an exercise for the reader is to check for and handle that with a simple if.

答案3

得分: 0

Sure, here is the translated code:

垃圾 = ['苹果', '小妖怪', '猫', '香蕉', '豆腐', '猫']

收集器 = ''
for i in range(len(垃圾)):
    if i == len(垃圾) - 1:
        收集器 += '和%s' % 垃圾[i]
    else:
        收集器 += '%s,' % 垃圾[i]

print(收集器)

Please note that I've translated the variable names and the list elements into Chinese while keeping the code structure the same.

英文:
garbage = [&#39;apples&#39;, &#39;goblins&#39;, &#39;cats&#39;, &#39;bananas&#39;, &#39;tofu&#39;, &#39;cats&#39;]

collector = &#39;&#39;
for i in range(len(garbage)):
    if i == len(garbage)-1: collector += &#39;and %s&#39; % garbage[i]
    else: collector += &#39;%s, &#39; % garbage[i]

print(collector)

huangapple
  • 本文由 发表于 2023年6月13日 09:01:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76461117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定