简体   繁体   English

在python中使用.join方法删除列表中的第一项和最后一项

[英]using .join method in python removes first and last items in list

I'm trying to get the string representation of my class correct. 我正在尝试正确显示类的字符串表示形式。 To do this I need to concatenate several lists into a string. 为此,我需要将几个列表连接成一个字符串。 The lists should be whitespace separated in the string. 列表应在字符串中用空格分隔。

These are my lists: 这些是我的清单:

[['C', 'A'], ['C', '2'], ['C', '3'], ['C', '4'], ['C', '5'], ['C', '6'], ['C', '7'], ['C', '8'], ['C', '9'], ['C', 'T'], ['C', 'J'], ['C', 'Q'], ['C', 'K'], ['S', 'A'], ['S', '2'], ['S', '3'], ['S', '4'], ['S', '5'], ['S', '6'], ['S', '7'], ['S', '8'], ['S', '9'], ['S', 'T'], ['S', 'J'], ['S', 'Q'], ['S', 'K'], ['H', 'A'], ['H', '2'], ['H', '3'], ['H', '4'], ['H', '5'], ['H', '6'], ['H', '7'], ['H', '8'], ['H', '9'], ['H', 'T'], ['H', 'J'], ['H', 'Q'], ['H', 'K'], ['D', 'A'], ['D', '2'], ['D', '3'], ['D', '4'], ['D', '5'], ['D', '6'], ['D', '7'], ['D', '8'], ['D', '9'], ['D', 'T'], ['D', 'J'], ['D', 'Q'], ['D', 'K']]

This is the code I use to join them: 这是我用来加入他们的代码:

    def __str__(self):
    str_deck_cards = 'Deck contains '
    for t in self.deck_cards:
        str_deck_cards += ' '.join(t)
    return str_deck_cards

However my output looks like this: 但是我的输出看起来像这样:

Deck contains C AC 2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KS AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KH AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KD AD 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD K

Why is it not joining the lists correctly? 为什么不能正确加入列表?

I've also tried with set() 我也尝试过set()

    def __str__(self):
    str_deck_cards = 'Deck contains '
    for t in self.deck_cards:
        str_deck_cards += ' '.join(set(t))
    return str_deck_cards

But it still doesn't get it right. 但是它仍然没有正确。 I'm out of ideas now, any suggestions? 我现在没主意了,有什么建议吗?

The .join takes an iterable and adds the string you wanted BETWEEN the items. .join采取可迭代的方式,并在项目之间添加所需的字符串。 So this works as expected. 因此,这按预期工作。

What you want is that when concatenating the strings generated, a whitespace is added so - 您想要的是在串联生成的字符串时,添加空格,以便-

str_deck_cards += ' '.join(t) + ' '

of course, at the end, if necessary, you'll have to get rid of the trailing whitespace. 当然,最后,如果需要,您必须摆脱尾随的空白。

== Edit == ==编辑==

you could also do something like that: 您也可以这样做:

return 'Deck contains ' + ' '.join([' '.join(x) for x in self.deck_cards])

Actually nothing is removed. 实际上什么也没有删除。 You are placing a space between two characters in a sublist C AC 2 not between two sublists CA C2 . 您在子列表C AC 2中的两个字符之间而不是在两个子列表CA C2之间放置空格。 So replace : 所以替换:

str_deck_cards += ' '.join(set(t)) # gives C AC 2C 3C 4C 5...

by: 通过:

str_deck_cards +=''.join(t)+' ' # gives CA C2 C3 C4 C5...

This will fix the issue. 这样可以解决问题。

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

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