list to string using "".join() – issues with passing a list of lists of strings

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

list to string using "".join() - issues with passing a list of lists of strings

问题

I feel like maybe this is an issue with using "".join() with a list of lists of strings instead of a list of strings, but haven't found an answer.

可能是因为在使用"".join()时,您正在使用字符串列表的列表而不是字符串列表,但尚未找到答案。

Maybe it's something else that I am missing.

也许还有其他我遗漏的问题。

I hope my notes show what I have been trying (to take a list of strings turn them into a str and append 'scramble' with that string)

我希望我的注释显示了我一直在尝试的内容(将字符串列表转换为字符串并将'scramble'附加到该字符串)

英文:

I feel like maybe this is an issue with using "".join() with a list of lists of strings instead of a list of strings, but haven't found an answer.

Maybe it's something else that I am missing.

I hope my notes show what I have been trying (to take a list of strings turn them into a str and append 'scramble' with that string)

# SCRAMBLE WORD/PHRASE
# IMPORTS
import random

# VARIABLES
test_words_list = ["dark", "happy holidays", "computer", "I like pie", "dogs love pizza"]

# FUNCTIONS
#function too big? cut down into smaller? or too small to be worth it?

def scramble_string(string, seperate_words = False):
  scramble = ""
  if seperate_words == False:
    """Remove spaces & scramble all letters together into one string"""
    words_list = string.split(" ")          # removes whitespace (list)
    print(f"letters_list= {words_list}")
    for word_str in words_list:
      word_letter_list = [letter for letter in word_str]
      print(f"word_letters_list = {word_letter_list}")
      random.shuffle(word_letter_list)
      print(f"After shuffle word_letters_list = {word_letter_list}")
      word_letter_str = "".join(word_letter_list)
      print(f"word_letter_str = {word_letter_str}")
      scramble += word_letter_str
      print(f"scramble = {scramble}")
    return scramble
  else:
    """scramble letters in words without mixing letters from different words.
    List words in same order with space between, but with letters scrambled"""
    scrambled_list = []
    words_list = string.split()                      # passed string into list of strings
    print(f"words_list = {words_list}")
    for word_str in words_list:
      letters_list = [letter for letter in word_str]
      print(f"letters_list = {letters_list}")
      random.shuffle(letters_list)
      print(f"After shuffle letters_list = {letters_list}")
      scrambled_list.append(letters_list)            # list of lists
      print(f"scrambled_list = {scrambled_list}")

      # vv PROBLEM vv
      scrambled_str = "".join(scrambled_list)  #"sequence item 0: expected str instance, list found"
      scramble += scrambled_str
      #scramble = ''.join(str(scrambled_list)[1:-1]) # makes scramble a list???
      print(f"scramble = {scramble}")
  return scramble

# Tests

#print(scramble_string(test_words_list[1]))          # WORKS (returned = "hyppahadsilyo")
print(scramble_string(test_words_list[-1], True))    # returns =

答案1

得分: 0

更新您的字符串列表到首先是字符串列表。我在这一行做了这个。

scrambled_list.append("".join(letters_list))            # 字符串列表

不是将字符串列表附加到列表中,而是将那个字母列表组合成一个单词,然后将那个打乱的单词附加到scrambled_list中。

import random

# 变量
test_words_list = ["dark", "happy holidays", "computer", "I like pie", "dogs love pizza"]

# 函数
# 函数太大了吗?要分割成更小的函数吗?还是太小不值得?
def scramble_string(string, separate_words=False):
    scramble = ""
    if separate_words == False:
        """Remove spaces & scramble all letters together into one string"""
        words_list = string.split(" ")      # 移除空格 (列表)
        print(f"letters_list= {words_list}")
        for word_str in words_list:
            word_letter_list = [letter for letter in word_str]
            print(f"word_letters_list = {word_letter_list}")
            random.shuffle(word_letter_list)
            print(f"After shuffle word_letters_list = {word_letter_list}")
            word_letter_str = "".join(word_letter_list)
            print(f"word_letter_str = {word_letter_str}")
            scramble += word_letter_str
            print(f"scramble = {scramble}")
        return scramble
    else:
        """scramble letters in words without mixing letters from different words.
        List words in same order with space between, but with letters scrambled"""
        scrambled_list = []
        words_list = string.split()                      # 将字符串转换成字符串列表
        print(f"words_list = {words_list}")
        for word_str in words_list:
            letters_list = [letter for letter in word_str]
            print(f"letters_list = {letters_list}")
            random.shuffle(letters_list)
            print(f"After shuffle letters_list = {letters_list}")
            scrambled_list.append("".join(letters_list))        # 字符串列表
            print(f"scrambled_list = {scrambled_list}")

        # vv 问题 vv
        scrambled_str = "".join(scrambled_list)  # "sequence item 0: expected str instance, list found"
        scramble += scrambled_str
        #scramble = ''.join(str(scrambled_list)[1:-1]) # makes scramble a list???
        print(f"scramble = {scramble}")
    return scramble

# 测试

# print(scramble_string(test_words_list[1]))          # 工作正常 (返回 = "hyppahadsilyo")
print(scramble_string(test_words_list[-1], True))
英文:

Update your list of list of string to list of string first. I did that at this line.

scrambled_list.append("".join(letters_list))            # list of lists

Instead of appending list of strings to a list, I am combining that list of letters to form a word and appending that scrambled word to the scrambled_list.

import random
# VARIABLES
test_words_list = ["dark", "happy holidays", "computer", "I like pie", "dogs love pizza"]
# FUNCTIONS
#function too big? cut down into smaller? or too small to be worth it?
def scramble_string(string, seperate_words = False):
scramble = ""
if seperate_words == False:
"""Remove spaces & scramble all letters together into one string"""
words_list = string.split(" ")		  # removes whitespace (list)
print(f"letters_list= {words_list}")
for word_str in words_list:
word_letter_list = [letter for letter in word_str]
print(f"word_letters_list = {word_letter_list}")
random.shuffle(word_letter_list)
print(f"After shuffle word_letters_list = {word_letter_list}")
word_letter_str = "".join(word_letter_list)
print(f"word_letter_str = {word_letter_str}")
scramble += word_letter_str
print(f"scramble = {scramble}")
return scramble
else:
"""scramble letters in words without mixing letters from different words.
List words in same order with space between, but with letters scrambled"""
scrambled_list = []
words_list = string.split()					  # passed string into list of strings
print(f"words_list = {words_list}")
for word_str in words_list:
letters_list = [letter for letter in word_str]
print(f"letters_list = {letters_list}")
random.shuffle(letters_list)
print(f"After shuffle letters_list = {letters_list}")
scrambled_list.append("".join(letters_list))			# list of lists
print(f"scrambled_list = {scrambled_list}")
# vv PROBLEM vv
scrambled_str = "".join(scrambled_list)  #"sequence item 0: expected str instance, list found"
scramble += scrambled_str
#scramble = ''.join(str(scrambled_list)[1:-1]) # makes scramble a list???
print(f"scramble = {scramble}")
return scramble
# Tests
# print(scramble_string(test_words_list[1]))		  # WORKS (returned = "hyppahadsilyo")
print(scramble_string(test_words_list[-1], True))

答案2

得分: 0

这是目前已经正确工作的函数(带有基本改进),供将来遇到类似问题的人参考。

# 扰乱单词/短语
# 导入
import random

# 变量
test_words_list = ["dark", "happy holidays", "computer", "I like pie", "dogs love pizza"]

# 函数

def scramble_string(string: str, seperate_words = False) -> str:
  string = string.lower()
  scramble = ""
  if seperate_words == False:
    """Remove spaces & scramble all letters together into one string"""
    words_list = string.split(" ")          
    for word_str in words_list:
      word_letter_list = [letter for letter in word_str]    # 每个单词中字母的列表
      random.shuffle(word_letter_list)
      scrambled_word_str = "".join(word_letter_list)
      scramble += scrambled_word_str
  else:
    """scramble letters in words WITHOUT mixing letters from different words.
    List scrambled words in orginal order (with space between)"""
    words_list = string.split()
    for word in words_list:
      scrambled_list = [letter for letter in word]
      random.shuffle(scrambled_list)
      scrambled_str = "".join(scrambled_list)
      scrambled_str += " "                           # 在字符串中单词之间添加空格
      scramble += scrambled_str
  return scramble

# 测试
print(scramble_string(test_words_list[-2]))           # 工作正常(返回值 = "hyppahadsilyo")
print(scramble_string(test_words_list[-1], True))    # 工作正常(返回值 = "sdog eovl zapzi")

# 工作笔记(用于跟踪和从错误中学习)
# 错误来源:scrambled_list.append(letters_list)
# 失败的解决方案(使scramble成为列表):scramble = ''.join(str(scrambled_list)[1:-1])
# 解决方案(错误:“sequence item 0: expected str instance, list found”):scrambled_list.append("".join(letters_list))
# 错误已解决(将字符串列表的列表给予"".join):scrambled_str = "".join(scrambled_list)
英文:

This is the function now working correctly (with basic improvements) for anyone with a similar issue in the future.

# SCRAMBLE WORD/PHRASE
# IMPORTS
import random
# VARIABLES
test_words_list = ["dark", "happy holidays", "computer", "I like pie", "dogs love pizza"]
# FUNCTIONS
def scramble_string(string: str, seperate_words = False) -> str:
string = string.lower()
scramble = ""
if seperate_words == False:
"""Remove spaces & scramble all letters together into one string"""
words_list = string.split(" ")          
for word_str in words_list:
word_letter_list = [letter for letter in word_str]    # list of letter in word for each word in words_list
random.shuffle(word_letter_list)
scrambled_word_str = "".join(word_letter_list)
scramble += scrambled_word_str
else:
"""scramble letters in words WITHOUT mixing letters from different words.
List scrambled words in orginal order (with space between)"""
words_list = string.split()
for word in words_list:
scrambled_list = [letter for letter in word]
random.shuffle(scrambled_list)
scrambled_str = "".join(scrambled_list)
scrambled_str += " "                           # Add space between words in string
scramble += scrambled_str
return scramble
# Tests
print(scramble_string(test_words_list[-2]))           # WORKS (returned = "hyppahadsilyo")
print(scramble_string(test_words_list[-1], True))    # WORKS (returned = "sdog eovl zapzi")
# Working Notes (to track & learn from mistakes)
# Error SOURCE: scrambled_list.append(letters_list)   
# Failed Solution(makes scramble a list): scramble = ''.join(str(scrambled_list)[1:-1])  
# Soultion(Error: "sequence item 0: expected str instance, list found") scrambled_list.append("".join(letters_list))
# Error RESOLVED (list of lists of strings given to "".join): scrambled_str = "".join(scrambled_list)  

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

发表评论

匿名网友

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

确定